Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(network): trust the endpoints the user enters themselves

pi-desktopa301ac7be4de
diff --git a/apps/desktop/electron/main/endpoint-policy.ts b/apps/desktop/electron/main/endpoint-policy.ts
new file mode 100644
index 000000000..2c3e1c809
--- /dev/null
+++ b/apps/desktop/electron/main/endpoint-policy.ts
@@ -0,0 +1,25 @@
+/**
+ * The user's plaintext opt-in for endpoints they enter themselves, as the main
+ * process currently holds it.
+ *
+ * The judgement of what an address *is* lives in `@pi-desktop/shared`
+ * (`public-network.ts`); whether the user accepted a plaintext hop to their own
+ * LAN service lives in the stored app settings (`networkPolicy`). The public
+ * network client runs synchronously per request, so the settings value is
+ * mirrored here whenever the host hands the app its settings, exactly as
+ * `network-proxy.ts` mirrors the proxy.
+ */
+import { allowInsecureUserEndpoints } from "@pi-desktop/shared";
+
+let applied = false;
+
+/** Mirror the stored `networkPolicy` section; returns the effective flag. */
+export function applyUserEndpointPolicyFromAppSettings(settings: unknown): boolean {
+ applied = allowInsecureUserEndpoints(settings);
+ return applied;
+}
+
+/** Whether plain `http` is currently allowed for a user-supplied endpoint. */
+export function allowInsecureUserEndpointsEnabled(): boolean {
+ return applied;
+}
diff --git a/apps/desktop/electron/main/git-clone.ts b/apps/desktop/electron/main/git-clone.ts
index a743a4065..dc267a0d5 100644
--- a/apps/desktop/electron/main/git-clone.ts
+++ b/apps/desktop/electron/main/git-clone.ts
@@ -5,6 +5,7 @@ import {
isGitCloneRepoName,
parseGitCloneUrl,
} from "../../src/lib/git-clone-url.ts";
+import { allowInsecureUserEndpointsEnabled } from "./endpoint-policy.ts";
export { parseGitCloneUrl } from "../../src/lib/git-clone-url.ts";
@@ -70,7 +71,9 @@ export async function cloneGitRepository(input: {
name?: string;
run?: typeof runGitClone;
}): Promise<string> {
- const target = parseGitCloneUrl(input.url);
+ const target = parseGitCloneUrl(input.url, {
+ allowInsecureHttp: allowInsecureUserEndpointsEnabled(),
+ });
if (!target) {
throw codedError("INVALID_ARGUMENT", "Enter a git repository URL");
}
diff --git a/apps/desktop/electron/main/mcp-oauth.ts b/apps/desktop/electron/main/mcp-oauth.ts
index 9f3d0544c..75ecf830c 100644
--- a/apps/desktop/electron/main/mcp-oauth.ts
+++ b/apps/desktop/electron/main/mcp-oauth.ts
@@ -1,8 +1,13 @@
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
-import type { McpOAuthLoginEvent, McpServerRecord, McpServerStatus } from "@pi-desktop/shared";
-
+import {
+ isUserSuppliedHostname,
+ type McpOAuthLoginEvent,
+ type McpServerRecord,
+ type McpServerStatus,
+} from "@pi-desktop/shared";
+import { allowInsecureUserEndpointsEnabled } from "./endpoint-policy.ts";
export type StoredMcpOAuthToken = {
clientId: string;
clientSecret?: string;
@@ -67,8 +72,22 @@ export function isLoopbackHostname(hostname: string): boolean {
return /^127(?:\.\d{1,3}){3}$/.test(host);
}
-/** OAuth 2.1: authorization-server endpoints must be HTTPS, except loopback. */
-export function assertTlsProtectedUrl(raw: string, label: string): URL {
+/**
+ * OAuth 2.1: authorization-server endpoints must be HTTPS, except on a host the
+ * user runs themselves.
+ *
+ * Loopback over plain `http` is the RFC 8252 shape and always passes. Any other
+ * plaintext URL passes only when the user has enabled insecure user endpoints in
+ * settings **and** it names the same host as the MCP server they typed
+ * (`trustedUrl`). Every other URL this guard sees arrives inside server metadata
+ * — `WWW-Authenticate`, a protected-resource or authorization-server document —
+ * so a server must not be able to send the app to a plaintext internal address
+ * the user never entered. `https` needs no such anchor.
+ *
+ * The refusal names both ways out: switch to HTTPS, or accept plaintext in
+ * settings.
+ */
+export function assertTlsProtectedUrl(raw: string, label: string, trustedUrl?: string): URL {
let url: URL;
try {
url = new URL(raw);
@@ -76,10 +95,37 @@ export function assertTlsProtectedUrl(raw: string, label: string): URL {
throw new Error(`${label} is not a valid URL`);
}
if (url.protocol === "https:") return url;
- if (url.protocol === "http:" && isLoopbackHostname(url.hostname)) return url;
+ if (url.protocol === "http:") {
+ if (isLoopbackHostname(url.hostname)) return url;
+ if (
+ allowInsecureUserEndpointsEnabled() &&
+ trustedUrl !== undefined &&
+ isUserSuppliedHostname(url.hostname) &&
+ sameHostname(trustedUrl, url.hostname)
+ ) {
+ return url;
+ }
+ throw new Error(
+ `${label} must use HTTPS (got ${url.protocol}//${url.host}); use HTTPS or enable plaintext endpoints for hosts you entered yourself in settings`,
+ );
+ }
throw new Error(`${label} must use HTTPS (got ${url.protocol}//${url.host})`);
}
+/** Host equality for a URL or a bare host, ignoring brackets, case and a dot. */
+function sameHostname(left: string, right: string): boolean {
+ const host = (value: string): string => {
+ const bare = value.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
+ try {
+ return new URL(value).hostname.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
+ } catch {
+ return bare;
+ }
+ };
+ const target = host(left);
+ return target !== "" && target === host(right);
+}
+
export function loopbackRedirectUri(port: number): string {
return `http://127.0.0.1:${port}/callback`;
}
@@ -192,7 +238,7 @@ export class McpOAuthManager {
// Best-effort probe; fallback to standard paths below.
}
if (resourceMetadataUrl) {
- assertTlsProtectedUrl(resourceMetadataUrl, "resource_metadata");
+ assertTlsProtectedUrl(resourceMetadataUrl, "resource_metadata", serverUrl);
}
// Step 2: Fallback to standard RFC 9728 paths if not in WWW-Authenticate
@@ -227,7 +273,7 @@ export class McpOAuthManager {
? (prm.authorization_servers as string[])
: [];
const authServer = authServersRaw[0] ?? urlObj.origin;
- assertTlsProtectedUrl(authServer, "authorization_server");
+ assertTlsProtectedUrl(authServer, "authorization_server", serverUrl);
const authServerObj = new URL(authServer);
// Step 3: Fetch Authorization Server Metadata (RFC 8414)
@@ -259,12 +305,12 @@ export class McpOAuthManager {
);
}
- assertTlsProtectedUrl(authorizationEndpoint, "authorization_endpoint");
- assertTlsProtectedUrl(tokenEndpoint, "token_endpoint");
+ assertTlsProtectedUrl(authorizationEndpoint, "authorization_endpoint", serverUrl);
+ assertTlsProtectedUrl(tokenEndpoint, "token_endpoint", serverUrl);
const registrationEndpoint =
typeof asMeta?.registration_endpoint === "string" ? asMeta.registration_endpoint : undefined;
if (registrationEndpoint) {
- assertTlsProtectedUrl(registrationEndpoint, "registration_endpoint");
+ assertTlsProtectedUrl(registrationEndpoint, "registration_endpoint", serverUrl);
}
const scopesSupported = Array.isArray(asMeta?.scopes_supported)
? (asMeta.scopes_supported as string[])
@@ -288,9 +334,10 @@ export class McpOAuthManager {
async registerClient(
registrationEndpoint: string,
redirectUris: string | string[],
+ trustedUrl?: string,
clientName = "PI-Desktop",
): Promise<{ clientId: string; clientSecret?: string }> {
- assertTlsProtectedUrl(registrationEndpoint, "registration_endpoint");
+ assertTlsProtectedUrl(registrationEndpoint, "registration_endpoint", trustedUrl);
const uris = Array.isArray(redirectUris) ? redirectUris : [redirectUris];
const res = await this.fetch(registrationEndpoint, {
method: "POST",
@@ -326,16 +373,21 @@ export class McpOAuthManager {
private async registerLoopbackClient(
registrationEndpoint: string,
exactRedirect: string,
+ trustedUrl: string,
): Promise<{ clientId: string; clientSecret?: string; redirectUris: string[] }> {
const portless = [LOOPBACK_REDIRECT_PORTLESS, exactRedirect];
try {
- const registered = await this.registerClient(registrationEndpoint, portless);
+ const registered = await this.registerClient(registrationEndpoint, portless, trustedUrl);
return { ...registered, redirectUris: portless };
} catch (error) {
this.deps.log?.("info", "mcp oauth portless DCR rejected, registering exact redirect", {
message: error instanceof Error ? error.message : String(error),
});
- const registered = await this.registerClient(registrationEndpoint, [exactRedirect]);
+ const registered = await this.registerClient(
+ registrationEndpoint,
+ [exactRedirect],
+ trustedUrl,
+ );
return { ...registered, redirectUris: [exactRedirect] };
}
}
@@ -627,6 +679,7 @@ export class McpOAuthManager {
const registered = await this.registerLoopbackClient(
metadata.registrationEndpoint,
redirectUri,
+ session.serverUrl,
);
clientId = registered.clientId;
clientSecret = registered.clientSecret;
@@ -848,7 +901,7 @@ export class McpOAuthManager {
if (!token.refreshToken) {
throw new Error("Token refresh failed: missing refresh_token");
}
- assertTlsProtectedUrl(token.tokenEndpoint, "token_endpoint");
+ assertTlsProtectedUrl(token.tokenEndpoint, "token_endpoint", token.resource);
const params = new URLSearchParams({
grant_type: "refresh_token",
client_id: token.clientId,
diff --git a/apps/desktop/electron/main/mcp-registry-catalog.ts b/apps/desktop/electron/main/mcp-registry-catalog.ts
index 0f5950ec0..23f44993f 100644
--- a/apps/desktop/electron/main/mcp-registry-catalog.ts
+++ b/apps/desktop/electron/main/mcp-registry-catalog.ts
@@ -18,22 +18,27 @@
import { net, session } from "electron";
import { lookup } from "node:dns/promises";
import { request as httpsRequest } from "node:https";
+import { request as httpRequest } from "node:http";
import type { IncomingHttpHeaders } from "node:http";
import { isIP } from "node:net";
import {
classifyIpLiteral,
classifyProxyRoute,
isAcceptableResolvedAddress,
+ isAcceptableUserEndpointAddress,
isSafeMarketSourceUrl,
+ isSafePublicHttpsUrl,
mapRegistryServer,
sanitizeMarketSources,
validateMcpCatalogFile,
+ type EndpointOrigin,
type MarketSource,
type PublicNetworkRoute,
type RegistryRecord,
type SourcedCatalogEntry,
} from "@pi-desktop/shared";
import { currentNetworkProxy } from "./network-proxy";
+import { allowInsecureUserEndpointsEnabled } from "./endpoint-policy";
const PAGE_SIZE = 100;
/** First browse paints two pages; every "load more" appends this many. */
@@ -100,8 +105,19 @@ async function resolveProxyRoute(url: string, timeoutMs: number): Promise<Public
* the connection. The caller must not resolve the hostname again: doing so
* would reopen a DNS-rebinding race between the policy check and the socket.
*/
-async function resolvePublicUrl(url: string, timeoutMs: number): Promise<ResolvedAddress> {
- if (!isSafeMarketSourceUrl(url)) {
+async function resolvePublicUrl(
+ url: string,
+ timeoutMs: number,
+ origin: EndpointOrigin,
+): Promise<ResolvedAddress> {
+ const userSupplied = origin === "user";
+ // A source URL the user typed may be a LAN or loopback catalog; plain http
+ // needs the stored opt-in. Every redirect target is judged by the public-only
+ // policy instead, so a source cannot hand the app an internal address to dial.
+ const accepted = userSupplied
+ ? isSafeMarketSourceUrl(url, { allowInsecureHttp: allowInsecureUserEndpointsEnabled() })
+ : isSafePublicHttpsUrl(url);
+ if (!accepted) {
throw new Error("url rejected by the public-network policy");
}
const deadline = Date.now() + timeoutMs;
@@ -123,10 +139,10 @@ async function resolvePublicUrl(url: string, timeoutMs: number): Promise<Resolve
const allowFakeIp = currentNetworkProxy().allowFakeIp === true;
for (const address of addresses) {
const addressKind = classifyIpLiteral(address.address);
- if (
- !isAcceptableResolvedAddress(addressKind, route) &&
- !(allowFakeIp && addressKind === "benchmark")
- ) {
+ const acceptable = userSupplied
+ ? isAcceptableUserEndpointAddress(address.address, addressKind, route)
+ : isAcceptableResolvedAddress(addressKind, route);
+ if (!acceptable && !(allowFakeIp && addressKind === "benchmark")) {
throw new Error(
`hostname resolves to a non-public address: ${host} -> ${address.address} (${addressKind}, ${route} route)`,
);
@@ -149,6 +165,9 @@ function requestPinnedHttps(
resolved: ResolvedAddress,
timeoutMs: number,
): Promise<PolicyResponse> {
+ // The name keeps its history: for a source URL that is `https` this is the
+ // SSL-pinning path, and for one the user typed as `http` it is the same path
+ // with the plaintext module and the same pinned address.
const parsed = new URL(url);
const host = parsed.hostname.startsWith("[")
? parsed.hostname.slice(1, -1)
@@ -166,15 +185,21 @@ function requestPinnedHttps(
clearDeadline();
reject(error);
};
- const req = httpsRequest(
+ const secure = parsed.protocol === "https:";
+ // A plaintext LAN source is a user endpoint under the stored opt-in, so the
+ // pinned path speaks http for it too. The address pinned to the socket is
+ // still the one the guard checked, and the Host header is still the original
+ // host (there is no SNI on a plaintext connection).
+ const send = (secure ? httpsRequest : httpRequest) as typeof httpsRequest;
+ const req = send(
{
- protocol: "https:",
+ protocol: parsed.protocol,
hostname: resolved.address,
family: resolved.family,
...(parsed.port ? { port: parsed.port } : {}),
path: `${parsed.pathname}${parsed.search}`,
method: "GET",
- servername: isIP(host) ? undefined : host,
+ ...(secure ? { servername: isIP(host) ? undefined : host } : {}),
headers: {
Host: parsed.host,
Accept: "application/json, text/plain;q=0.9",
@@ -287,7 +312,11 @@ async function fetchPolicy<T>(url: string, kind: "json" | "text"): Promise<T> {
for (let hop = 0; hop <= MAX_HOPS; hop += 1) {
const remaining = deadline - Date.now();
if (remaining <= 0) throw new Error("market source request timed out");
- const resolved = await resolvePublicUrl(current, remaining);
+ const resolved = await resolvePublicUrl(
+ current,
+ remaining,
+ hop === 0 ? "user" : "third-party",
+ );
const response =
resolved.route === "proxied"
? await requestProxiedHttps(current, deadline - Date.now())
@@ -465,10 +494,15 @@ export function createMcpMarketAggregator() {
options: { more?: boolean } = {},
): Promise<McpRegistrySearchResult> {
const trimmed = String(query ?? "").trim().toLowerCase().slice(0, MAX_QUERY_LENGTH);
- const configured = sanitizeMarketSources(sources).slice(0, MAX_MARKET_SOURCES);
- const safe = configured.filter((source) => isSafeMarketSourceUrl(source.url));
+ const insecure = allowInsecureUserEndpointsEnabled();
+ const configured = sanitizeMarketSources(sources, {
+ allowInsecureHttp: insecure,
+ }).slice(0, MAX_MARKET_SOURCES);
+ const safe = configured.filter((source) =>
+ isSafeMarketSourceUrl(source.url, { allowInsecureHttp: insecure }),
+ );
const failedSources = configured
- .filter((source) => !isSafeMarketSourceUrl(source.url))
+ .filter((source) => !isSafeMarketSourceUrl(source.url, { allowInsecureHttp: insecure }))
.map((source) => source.name);
if (trimmed) {
diff --git a/apps/desktop/electron/main/network-proxy.ts b/apps/desktop/electron/main/network-proxy.ts
index c2afd7af4..b6949cc9d 100644
--- a/apps/desktop/electron/main/network-proxy.ts
+++ b/apps/desktop/electron/main/network-proxy.ts
@@ -25,6 +25,7 @@ import {
startAuthenticatedProxyRelay,
type AuthenticatedProxyRelay,
} from "@pi-desktop/agent-runtime";
+import { applyUserEndpointPolicyFromAppSettings } from "./endpoint-policy";
const originalEnv = snapshotProxyEnv(process.env);
let applied: NetworkProxySettings = { mode: "system" };
@@ -78,6 +79,9 @@ export async function applyNetworkProxy(
export async function applyNetworkProxyFromAppSettings(
settings: unknown,
): Promise<NetworkProxySettings> {
+ // The plaintext opt-in for user-supplied endpoints rides the same settings
+ // write as the proxy, so one call site mirrors both.
+ applyUserEndpointPolicyFromAppSettings(settings);
const record =
settings && typeof settings === "object"
? (settings as { networkProxy?: unknown })
diff --git a/apps/desktop/electron/main/public-https-fetch.ts b/apps/desktop/electron/main/public-https-fetch.ts
index e8ccd0047..971ad1244 100644
--- a/apps/desktop/electron/main/public-https-fetch.ts
+++ b/apps/desktop/electron/main/public-https-fetch.ts
@@ -5,9 +5,12 @@ import {
classifyIpLiteral,
classifyProxyRoute,
isAcceptableResolvedAddress,
+ isAcceptableUserEndpointAddress,
isPublicNetworkPolicyFailure,
isSafePublicHttpsUrl,
+ isSafeUserEndpointUrl,
publicNetworkRefusalReason,
+ type EndpointOrigin,
type PublicNetworkAddressKind,
type PublicNetworkRefusalDetail,
type PublicNetworkRefusalReason,
@@ -108,9 +111,16 @@ export function isPublicNetworkPolicyError(error: unknown): boolean {
return error instanceof PublicNetworkPolicyError || isPublicNetworkPolicyFailure(error);
}
+/** The shared origin type, under the name this module's callers already use. */
+export type PublicHttpsEndpointOrigin = EndpointOrigin;
+
export type PublicHttpsClient = {
- assertPublicUrl: (url: string) => Promise<void>;
- request: (url: string, kind: "json" | "text") => Promise<unknown>;
+ assertPublicUrl: (url: string, origin?: PublicHttpsEndpointOrigin) => Promise<void>;
+ request: (
+ url: string,
+ kind: "json" | "text",
+ origin?: PublicHttpsEndpointOrigin,
+ ) => Promise<unknown>;
};
/**
@@ -129,6 +139,11 @@ export type PublicHttpsClient = {
* the resolver-artifact class is tolerated there, and every class that names a
* real internal target still refuses. A route the transport cannot name keeps
* the strict verdict (ADR 0272).
+ *
+ * A hop is judged for the origin that chose its address: a user-supplied
+ * endpoint may resolve to the user's own loopback or LAN, while every hop the
+ * app learned from someone else — a redirect in particular — keeps the strict
+ * public-only rule.
*/
export function createPublicHttpsClient(options: {
fetchImpl: PublicHttpsFetch;
@@ -137,6 +152,11 @@ export function createPublicHttpsClient(options: {
routeImpl?: PublicHttpsRouteLookup;
/** Permit only benchmark fake-IP answers when the user explicitly opts in. */
allowFakeIp?: boolean | (() => boolean);
+ /**
+ * Permit plain `http` for a user-supplied endpoint, per the stored
+ * `networkPolicy`. Never widens the third-party policy.
+ */
+ allowInsecureUserEndpoints?: boolean | (() => boolean);
timeoutMs?: number;
}): PublicHttpsClient {
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -158,8 +178,28 @@ export function createPublicHttpsClient(options: {
}
}
- async function assertPublicUrl(url: string): Promise<void> {
- if (!isSafePublicHttpsUrl(url)) {
+ function insecureUserEndpointsAllowed(): boolean {
+ return typeof options.allowInsecureUserEndpoints === "function"
+ ? options.allowInsecureUserEndpoints()
+ : options.allowInsecureUserEndpoints === true;
+ }
+
+ /**
+ * Judge one hop for the origin that chose it. `user` is an endpoint the person
+ * typed into a settings field — their own machine, their own LAN service —
+ * and reaches loopback and private addresses under the stored policy.
+ * `third-party` is every hop this app learned from someone else and keeps the
+ * public-only rule.
+ */
+ async function assertPublicUrl(
+ url: string,
+ origin: PublicHttpsEndpointOrigin = "third-party",
+ ): Promise<void> {
+ const userSupplied = origin === "user";
+ const accepted = userSupplied
+ ? isSafeUserEndpointUrl(url, { allowInsecureHttp: insecureUserEndpointsAllowed() })
+ : isSafePublicHttpsUrl(url);
+ if (!accepted) {
throw new PublicNetworkPolicyError(`url rejected by the public-network policy: ${url}`, {
reason: "url-syntax",
});
@@ -194,10 +234,13 @@ export function createPublicHttpsClient(options: {
typeof options.allowFakeIp === "function"
? options.allowFakeIp()
: options.allowFakeIp === true;
- if (
- !isAcceptableResolvedAddress(addressKind, route) &&
- !(allowFakeIp && addressKind === "benchmark")
- ) {
+ // A user-supplied endpoint reaches the user's own loopback and LAN; a
+ // third-party hop keeps the public-only rule. Neither tolerates cloud
+ // metadata, and neither tolerates a fake-IP answer on a direct route.
+ const acceptable = userSupplied
+ ? isAcceptableUserEndpointAddress(address.address, addressKind, route)
+ : isAcceptableResolvedAddress(addressKind, route);
+ if (!acceptable && !(allowFakeIp && addressKind === "benchmark")) {
// The class travels with the refusal: `benchmark` is a TUN fake-IP
// (198.18.0.0/15) and `private` is a real RFC1918 target. The explicit
// fake-IP opt-in never changes the verdict for any other non-public
@@ -210,10 +253,17 @@ export function createPublicHttpsClient(options: {
}
}
- async function requestOnce(url: string, kind: "json" | "text"): Promise<unknown> {
+ async function requestOnce(
+ url: string,
+ kind: "json" | "text",
+ origin: PublicHttpsEndpointOrigin,
+ ): Promise<unknown> {
let current = url;
for (let hop = 0; hop <= MAX_HOPS; hop += 1) {
- await assertPublicUrl(current);
+ // Only the first hop is the address the user chose. Every redirect is a
+ // destination this app learned from someone else, so it is judged by the
+ // third-party policy without exception.
+ await assertPublicUrl(current, hop === 0 ? origin : "third-party");
const response = await options.fetchImpl(current, {
redirect: "manual",
signal: AbortSignal.timeout(timeoutMs),
@@ -230,11 +280,15 @@ export function createPublicHttpsClient(options: {
throw new PublicNetworkPolicyError("too many redirects", { reason: "redirect-limit" });
}
- async function request(url: string, kind: "json" | "text"): Promise<unknown> {
+ async function request(
+ url: string,
+ kind: "json" | "text",
+ origin: PublicHttpsEndpointOrigin = "third-party",
+ ): Promise<unknown> {
let lastError: unknown;
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
try {
- return await requestOnce(url, kind);
+ return await requestOnce(url, kind, origin);
} catch (error) {
lastError = error;
// A refusal the guard decided is final: a syntax rejection, a
diff --git a/apps/desktop/electron/main/skill-market-catalog.ts b/apps/desktop/electron/main/skill-market-catalog.ts
index f665347a6..e9c0b1e18 100644
--- a/apps/desktop/electron/main/skill-market-catalog.ts
+++ b/apps/desktop/electron/main/skill-market-catalog.ts
@@ -10,6 +10,7 @@ import { net, session } from "electron";
import type { SkillCatalogEntry, SkillMarketSource } from "@pi-desktop/shared";
import { createPublicHttpsClient } from "./public-https-fetch";
import { currentNetworkProxy } from "./network-proxy";
+import { allowInsecureUserEndpointsEnabled } from "./endpoint-policy";
import {
createSkillMarketAggregator,
type SkillMarketDocument,
@@ -29,8 +30,13 @@ const client = createPublicHttpsClient({
fetchImpl: (url, init) => net.fetch(url, init),
routeImpl: (url) => session.defaultSession.resolveProxy(url),
allowFakeIp: () => currentNetworkProxy().allowFakeIp === true,
+ // A source URL the user typed may be a LAN or loopback catalog; the opt-in
+ // for a plaintext hop to it is the stored `networkPolicy`.
+ allowInsecureUserEndpoints: () => allowInsecureUserEndpointsEnabled(),
+});
+const aggregator = createSkillMarketAggregator(client.request, {
+ allowInsecureUserEndpoints: () => allowInsecureUserEndpointsEnabled(),
});
-const aggregator = createSkillMarketAggregator(client.request);
export function searchSkillMarket(
query: string,
diff --git a/apps/desktop/electron/main/skill-market-scan.ts b/apps/desktop/electron/main/skill-market-scan.ts
index 61b067677..48b3fa043 100644
--- a/apps/desktop/electron/main/skill-market-scan.ts
+++ b/apps/desktop/electron/main/skill-market-scan.ts
@@ -7,11 +7,13 @@
import {
PUBLIC_NETWORK_POLICY_ERROR,
isProxyFakeIpAddress,
+ isSafePublicHttpsUrl,
isSafeSkillSourceUrl,
publicNetworkRefusalDetail,
sanitizeSkillCatalogId,
splitSkillDocument,
validateSkillCatalogFile,
+ type EndpointOrigin,
type PublicNetworkAddressKind,
type PublicNetworkRefusalReason,
type PublicNetworkRoute,
@@ -21,7 +23,11 @@ import {
type SourcedSkillEntry,
} from "@pi-desktop/shared";
-export type CatalogRequest = (url: string, kind: "json" | "text") => Promise<unknown>;
+export type CatalogRequest = (
+ url: string,
+ kind: "json" | "text",
+ origin?: EndpointOrigin,
+) => Promise<unknown>;
/**
* Why a source failed. `policy` means the guard judged an address (or the URL
@@ -190,22 +196,32 @@ export function guessSkillCategories(path: string): SkillCatalogCategory[] {
return ["workflow"];
}
-export function createSkillMarketAggregator(request: CatalogRequest) {
+export function createSkillMarketAggregator(
+ request: CatalogRequest,
+ policy: { allowInsecureUserEndpoints?: boolean | (() => boolean) } = {},
+) {
const catalogCache = new Map<string, { at: number; entries: SourcedSkillEntry[] }>();
const documentCache = new Map<string, { at: number; document: SkillMarketDocument }>();
- async function fetchJson<T>(url: string): Promise<T> {
- return (await request(url, "json")) as T;
+ async function fetchJson<T>(url: string, origin?: EndpointOrigin): Promise<T> {
+ return (await request(url, "json", origin)) as T;
}
- async function fetchText(url: string): Promise<string> {
- return (await request(url, "text")) as string;
+ async function fetchText(url: string, origin?: EndpointOrigin): Promise<string> {
+ return (await request(url, "text", origin)) as string;
+ }
+
+ /** Whether the stored policy accepts a plaintext hop to the user's own host. */
+ function insecureUserEndpointsAllowed(): boolean {
+ return typeof policy.allowInsecureUserEndpoints === "function"
+ ? policy.allowInsecureUserEndpoints()
+ : policy.allowInsecureUserEndpoints === true;
}
async function loadCatalog(source: SkillMarketSource): Promise<SourcedSkillEntry[]> {
const hit = catalogCache.get(source.url);
if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.entries;
- const body = await fetchJson<unknown>(source.url);
+ const body = await fetchJson<unknown>(source.url, "user");
const { catalog } = validateSkillCatalogFile(body);
const entries = catalog.skills.map((entry) => ({
...entry,
@@ -224,10 +240,12 @@ export function createSkillMarketAggregator(request: CatalogRequest) {
const [, owner, repo] = match;
const repoInfo = await fetchJson<{ default_branch?: string }>(
`https://api.github.com/repos/${owner}/${repo}`,
+ "user",
);
const branch = repoInfo.default_branch || "main";
const tree = await fetchJson<{ tree?: Array<{ path: string }> }>(
`https://api.github.com/repos/${owner}/${repo}/git/trees/${branch}?recursive=1`,
+ "user",
);
const entries: SourcedSkillEntry[] = [];
const seen = new Set<string>();
@@ -259,7 +277,7 @@ export function createSkillMarketAggregator(request: CatalogRequest) {
async function fetchDocument(url: string): Promise<SkillMarketDocument> {
const hit = documentCache.get(url);
if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.document;
- const document = splitSkillDocument(await fetchText(url)) as SkillMarketDocument;
+ const document = splitSkillDocument(await fetchText(url, "third-party")) as SkillMarketDocument;
const match = JSDELIVR_GH.exec(url);
if (match) {
const [, owner, repo, ref, path] = match;
@@ -267,6 +285,7 @@ export function createSkillMarketAggregator(request: CatalogRequest) {
try {
const listing = (await fetchJson<{ files?: Array<{ name: string }> }>(
`https://data.jsdelivr.com/v1/packages/gh/${owner}/${repo}@${ref}?structure=flat`,
+ "third-party",
)) as { files?: Array<{ name: string }> };
const siblings = (listing.files ?? [])
.map((file) => file.name)
@@ -275,7 +294,10 @@ export function createSkillMarketAggregator(request: CatalogRequest) {
for (const name of siblings.slice(0, 20)) {
resources.push({
path: name.slice(dir.length),
- body: await fetchText(`https://cdn.jsdelivr.net/gh/${owner}/${repo}@${ref}/${name}`),
+ body: await fetchText(
+ `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${ref}/${name}`,
+ "third-party",
+ ),
});
}
if (resources.length) document.resources = resources;
@@ -289,10 +311,13 @@ export function createSkillMarketAggregator(request: CatalogRequest) {
async function search(query: string, sources: SkillMarketSource[]): Promise<SkillMarketSearchResult> {
const trimmed = query.trim().toLocaleLowerCase();
- const usable = sources.filter((source) => isSafeSkillSourceUrl(source.url));
+ // A source URL the user typed may be a LAN or loopback catalog; plain http
+ // needs the stored opt-in. Plaintext never reaches a document URL.
+ const sourceOptions = { allowInsecureHttp: insecureUserEndpointsAllowed() };
+ const usable = sources.filter((source) => isSafeSkillSourceUrl(source.url, sourceOptions));
// A source the syntactic guard never let out is a policy refusal, not a
// transport failure, and it must not be reported as an unreachable host.
- const refused = sources.filter((source) => !isSafeSkillSourceUrl(source.url));
+ const refused = sources.filter((source) => !isSafeSkillSourceUrl(source.url, sourceOptions));
const failedSources = refused.map((source) => source.name);
// Two sources can carry the same display name (a default source and a user
// source with the same label), and `failedSources` already cannot tell such
@@ -361,7 +386,10 @@ export function createSkillMarketAggregator(request: CatalogRequest) {
}
async function fetchEntryDocument(entry: SkillCatalogEntry): Promise<SkillMarketDocument> {
- if (!isSafeSkillSourceUrl(entry.url)) {
+ // A document URL arrives inside a catalog the app did not receive from the
+ // user, so it keeps the public-only policy even when the source itself is a
+ // LAN catalog the user added.
+ if (!isSafePublicHttpsUrl(entry.url)) {
// A document URL the syntactic guard refuses is a decision about the URL,
// not a dead host. Carrying the shared name and reason means the one
// classifier reports it as the policy refusal it is, instead of telling
diff --git a/apps/desktop/src/components/HomeProjectSwitcher.tsx b/apps/desktop/src/components/HomeProjectSwitcher.tsx
index 4a1ab0b1e..3a3b9c96a 100644
--- a/apps/desktop/src/components/HomeProjectSwitcher.tsx
+++ b/apps/desktop/src/components/HomeProjectSwitcher.tsx
@@ -7,6 +7,7 @@ import {
type KeyboardEvent as ReactKeyboardEvent,
} from "react";
import { useTranslation } from "react-i18next";
+import { allowInsecureUserEndpoints } from "@pi-desktop/shared";
import { parseGitCloneUrl } from "../lib/git-clone-url";
import {
filterSwitcherProjects,
@@ -43,6 +44,7 @@ export function HomeProjectSwitcher({
const openProject = useAppStore((state) => state.openProject);
const cloneProject = useAppStore((state) => state.cloneProject);
const showToast = useAppStore((state) => state.showToast);
+ const settings = useAppStore((state) => state.settings);
const [open, setOpen] = useState(false);
const [view, setView] = useState<"list" | "clone">("list");
@@ -68,7 +70,9 @@ export function HomeProjectSwitcher({
[projects, query],
);
const activeKey = normalizeProjectPath(activeProjectPath ?? path);
- const cloneTarget = parseGitCloneUrl(cloneUrl);
+ const cloneTarget = parseGitCloneUrl(cloneUrl, {
+ allowInsecureHttp: allowInsecureUserEndpoints(settings),
+ });
const close = useCallback(() => {
setOpen(false);
diff --git a/apps/desktop/src/components/ProjectCreateDialog.tsx b/apps/desktop/src/components/ProjectCreateDialog.tsx
index 24deae598..94c8253d7 100644
--- a/apps/desktop/src/components/ProjectCreateDialog.tsx
+++ b/apps/desktop/src/components/ProjectCreateDialog.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { MAX_PROJECT_NAME_CHARS } from "../lib/sidebar-preferences";
import { api } from "../lib/api";
import { parseGitCloneUrl } from "../lib/git-clone-url";
+import { allowInsecureUserEndpoints } from "@pi-desktop/shared";
import {
defaultProjectName,
folderNameFromPath,
@@ -60,7 +61,10 @@ export function ProjectCreateDialog() {
const folderPickerInFlightRef = useRef(false);
// The picked source seeds the project name until the user types their own.
const nameTouchedRef = useRef(false);
- const cloneTarget = parseGitCloneUrl(gitUrl);
+ const settings = useAppStore((state) => state.settings);
+ const cloneTarget = parseGitCloneUrl(gitUrl, {
+ allowInsecureHttp: allowInsecureUserEndpoints(settings),
+ });
const defaultName = defaultProjectName({
source,
folders,
diff --git a/apps/desktop/src/components/settings/McpMarketPanel.tsx b/apps/desktop/src/components/settings/McpMarketPanel.tsx
index 12833c1e0..c603e9fd0 100644
--- a/apps/desktop/src/components/settings/McpMarketPanel.tsx
+++ b/apps/desktop/src/components/settings/McpMarketPanel.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react"
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
+ allowInsecureUserEndpoints,
BUILTIN_MCP_CATALOG,
DEFAULT_MARKET_SOURCE,
GLOBAL_SCOPE,
@@ -78,10 +79,12 @@ type MarketItem = McpCatalogEntry & { sourceId?: string };
const SOURCES_STORAGE_KEY = "pi.mcp-market.sources.v1";
-function loadSources(): MarketSource[] {
+function loadSources(allowInsecureHttp = false): MarketSource[] {
try {
const raw = window.localStorage?.getItem(SOURCES_STORAGE_KEY);
- return raw ? sanitizeMarketSources(JSON.parse(raw)) : [DEFAULT_MARKET_SOURCE];
+ return raw
+ ? sanitizeMarketSources(JSON.parse(raw), { allowInsecureHttp })
+ : [DEFAULT_MARKET_SOURCE];
} catch {
return [DEFAULT_MARKET_SOURCE];
}
@@ -121,6 +124,11 @@ export function McpMarketPanel({
const [saving, setSaving] = useState(false);
const [remote, setRemote] = useState<RemoteState>(REMOTE_IDLE);
const [sources, setSources] = useState<MarketSource[]>(loadSources);
+ // Whether a plaintext hop to a user-supplied source is allowed, from the
+ // stored `networkPolicy`. The panel validates its persisted list with the same
+ // rule the main process applies to the request, so a source the user accepted
+ // survives a reload and one they have not stays out.
+ const [allowInsecureSources, setAllowInsecureSources] = useState(false);
const requestGeneration = useRef(0);
const [sourcesOpen, setSourcesOpen] = useState(false);
const [draftSource, setDraftSource] = useState<{
@@ -130,8 +138,20 @@ export function McpMarketPanel({
}>({ name: "", url: "", kind: "registry" });
useEffect(() => {
- saveSources(sources);
- }, [sources]);
+ let cancelled = false;
+ void api
+ .getSettings()
+ .then((settings) => {
+ if (cancelled) return;
+ const insecure = allowInsecureUserEndpoints(settings);
+ setAllowInsecureSources(insecure);
+ if (insecure) setSources(loadSources(true));
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, []);
// Every configured source is queried live (debounced); built-in picks render
// immediately and stay as the offline floor when all sources are down.
@@ -383,7 +403,7 @@ export function McpMarketPanel({
const addSource = () => {
const url = draftSource.url.trim();
- if (!isSafeMarketSourceUrl(url)) {
+ if (!isSafeMarketSourceUrl(url, { allowInsecureHttp: allowInsecureSources })) {
showToast(t("settings.mcpMarket.sourceUnsafe"), { variant: "error" });
return;
}
diff --git a/apps/desktop/src/components/settings/NetworkProxySection.tsx b/apps/desktop/src/components/settings/NetworkProxySection.tsx
index fa9c6ad4e..ac1e14cc4 100644
--- a/apps/desktop/src/components/settings/NetworkProxySection.tsx
+++ b/apps/desktop/src/components/settings/NetworkProxySection.tsx
@@ -136,6 +136,23 @@ export function NetworkProxySection({
}
};
+ const insecureUserEndpoints =
+ settings.networkPolicy?.allowInsecureUserEndpoints === true;
+
+ /**
+ * Only the `networkPolicy` field is written: the settings write merges this
+ * patch into the stored settings, so every other preference is carried over
+ * untouched.
+ */
+ const persistUserEndpointPolicy = async (allowInsecureUserEndpoints: boolean) => {
+ setSaveError(false);
+ try {
+ await saveSettings({ networkPolicy: { allowInsecureUserEndpoints } });
+ } catch {
+ setSaveError(true);
+ }
+ };
+
return (
<section className="settings-card-block">
<h3 className="settings-card-heading">{t("settings.network")}</h3>
@@ -255,6 +272,33 @@ export function NetworkProxySection({
</>
) : null}
+ <SettingsRow
+ title={t("settings.networkAllowInsecureUserEndpoints")}
+ description={t("settings.networkAllowInsecureUserEndpointsDesc")}
+ >
+ <span className="settings-network-checkbox">
+ <input
+ type="checkbox"
+ checked={insecureUserEndpoints}
+ aria-label={t("settings.networkAllowInsecureUserEndpoints")}
+ aria-describedby="network-insecure-endpoints-warning"
+ onChange={(event) =>
+ void persistUserEndpointPolicy(event.target.checked)
+ }
+ />
+ </span>
+ </SettingsRow>
+
+ {insecureUserEndpoints ? (
+ <div
+ id="network-insecure-endpoints-warning"
+ className="settings-network-warning"
+ role="alert"
+ >
+ {t("settings.networkAllowInsecureUserEndpointsWarning")}
+ </div>
+ ) : null}
+
{saveError ? (
<span className="settings-command-shell-state error" role="status">
{t("settings.proxySaveError")}
diff --git a/apps/desktop/src/components/settings/SkillMarketPanel.tsx b/apps/desktop/src/components/settings/SkillMarketPanel.tsx
index 41b80f5ab..aead607d9 100644
--- a/apps/desktop/src/components/settings/SkillMarketPanel.tsx
+++ b/apps/desktop/src/components/settings/SkillMarketPanel.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react"
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
+ allowInsecureUserEndpoints,
assembleSkillInstall,
BUILTIN_SKILL_CATALOG,
GLOBAL_SCOPE,
@@ -105,10 +106,10 @@ const REMOTE_IDLE: RemoteState = {
const SOURCES_STORAGE_KEY = "pi.skill-market.sources.v1";
-function loadSources(): SkillMarketSource[] {
+function loadSources(allowInsecureHttp = false): SkillMarketSource[] {
try {
const raw = window.localStorage?.getItem(SOURCES_STORAGE_KEY);
- return raw ? sanitizeSkillSources(JSON.parse(raw)) : [];
+ return raw ? sanitizeSkillSources(JSON.parse(raw), { allowInsecureHttp }) : [];
} catch {
return [];
}
@@ -166,6 +167,10 @@ export function SkillMarketPanel({
const [installing, setInstalling] = useState(false);
const previewGate = useRef(new LatestWinsGate());
const [sources, setSources] = useState<SkillMarketSource[]>(loadSources);
+ // Whether a plaintext hop to a user-supplied source is allowed, from the
+ // stored `networkPolicy`: the panel re-validates its persisted list with the
+ // same rule the main process applies to the request.
+ const [allowInsecureSources, setAllowInsecureSources] = useState(false);
const [sourcesOpen, setSourcesOpen] = useState(false);
const [draftSource, setDraftSource] = useState<{ name: string; url: string }>({
name: "",
@@ -173,6 +178,22 @@ export function SkillMarketPanel({
});
const [remote, setRemote] = useState<RemoteState>(REMOTE_IDLE);
+ useEffect(() => {
+ let cancelled = false;
+ void api
+ .getSettings()
+ .then((settings) => {
+ if (cancelled) return;
+ const insecure = allowInsecureUserEndpoints(settings);
+ setAllowInsecureSources(insecure);
+ if (insecure) setSources(loadSources(true));
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
useEffect(() => {
saveSources(sources);
}, [sources]);
@@ -334,7 +355,7 @@ export function SkillMarketPanel({
const addSource = () => {
const url = draftSource.url.trim();
- if (!isSafeSkillSourceUrl(url)) {
+ if (!isSafeSkillSourceUrl(url, { allowInsecureHttp: allowInsecureSources })) {
showToast(t("settings.sklm.sourceUnsafe"), { variant: "error" });
return;
}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index e97a0492e..c5e3febf9 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -130,8 +130,10 @@ import {
normalizeLargePasteThreshold,
normalizeMode,
normalizeNetworkProxy,
+ normalizeNetworkPolicy,
resolveFontScale,
normalizeChatContentMaxWidth,
+ validateNetworkPolicy,
validateNetworkProxy,
validateSpeechSettings,
} from "@pi-desktop/shared";
@@ -366,6 +368,9 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
networkProxy: normalizeNetworkProxy(
(settings as { networkProxy?: unknown }).networkProxy,
),
+ networkPolicy: normalizeNetworkPolicy(
+ (settings as { networkPolicy?: unknown }).networkPolicy,
+ ),
};
}
@@ -386,6 +391,7 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {
chatContentMaxWidth?: unknown;
infiniteProviderRetry?: unknown;
networkProxy?: unknown;
+ networkPolicy?: unknown;
};
if (
Object.prototype.hasOwnProperty.call(value, "defaultCommandShell") &&
@@ -437,6 +443,15 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {
}
value.networkProxy = proxy.value;
}
+ if (Object.prototype.hasOwnProperty.call(value, "networkPolicy")) {
+ const policy = validateNetworkPolicy(value.networkPolicy);
+ if (!policy.ok) {
+ throw Object.assign(new Error(policy.error), {
+ errorCode: "INVALID_ARGUMENT",
+ });
+ }
+ value.networkPolicy = policy.value;
+ }
if (Object.prototype.hasOwnProperty.call(value, "speech")) {
(value as AppSettings).speech = validateSpeechSettings(
(value as { speech?: unknown }).speech,
diff --git a/apps/desktop/src/lib/git-clone-url.ts b/apps/desktop/src/lib/git-clone-url.ts
index 5722fdb75..7f31687b1 100644
--- a/apps/desktop/src/lib/git-clone-url.ts
+++ b/apps/desktop/src/lib/git-clone-url.ts
@@ -1,4 +1,4 @@
-import { isPublicHostname } from "@pi-desktop/shared";
+import { isUserSuppliedHostname } from "@pi-desktop/shared";
export type GitCloneTarget = {
url: string;
@@ -22,17 +22,26 @@ function repoNameFromPath(path: string): string | null {
return name;
}
-function isAllowedGitHost(host: string): boolean {
- return isPublicHostname(host);
-}
-
/**
- * Accept https/http/ssh/git URLs and `git@host:path` remotes. Reject
- * credentials-in-URL, file URLs, private/loopback/link-local hosts, and
- * names that cannot be a folder. Host checks are syntactic (ADR 0247);
- * git still performs its own DNS/SSH.
+ * A clone remote is an address the user typed, so it may be a LAN or loopback
+ * git host — a self-hosted GitLab on 192.168.x.x, a local `git daemon` — under
+ * the same trust rule as every other user-supplied endpoint. Cloud metadata
+ * hosts stay refused. Host checks are syntactic; git performs its own DNS/SSH.
+ *
+ * Plain `http`/`git` carries whatever credentials the endpoint accepts over a
+ * plaintext hop, so — like every other user-supplied endpoint — it needs the
+ * user's explicit `networkPolicy.allowInsecureUserEndpoints` opt-in
+ * (`allowInsecureHttp`); `https`, `ssh` and `git@host:path` need no opt-in and
+ * stay allowed by default.
*/
-export function parseGitCloneUrl(raw: string | null | undefined): GitCloneTarget | null {
+function isAllowedGitHost(host: string): boolean {
+ return isUserSuppliedHostname(host);
+}
+export function parseGitCloneUrl(
+ raw: string | null | undefined,
+ options?: { allowInsecureHttp?: boolean },
+): GitCloneTarget | null {
+ const allowInsecureHttp = options?.allowInsecureHttp === true;
const url = raw?.trim() ?? "";
if (!url || url.length > 2048 || /\s/.test(url)) return null;
@@ -52,6 +61,12 @@ export function parseGitCloneUrl(raw: string | null | undefined): GitCloneTarget
if (!["https:", "http:", "ssh:", "git:"].includes(parsed.protocol)) {
return null;
}
+ if (
+ (parsed.protocol === "http:" || parsed.protocol === "git:") &&
+ !allowInsecureHttp
+ ) {
+ return null;
+ }
if (parsed.password) return null;
if (!isAllowedGitHost(parsed.hostname)) return null;
const name = repoNameFromPath(parsed.pathname);
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index 0e9067a25..239a250b1 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -73,6 +73,8 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
"settings.proxyCustom",
"settings.proxyUrl",
"settings.proxyFakeIp",
+ "settings.networkAllowInsecureUserEndpoints",
+ "settings.networkAllowInsecureUserEndpointsDesc",
],
},
{
diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.css
index 08dda764c..7f014e6bb 100644
--- a/apps/desktop/src/styles/settings.css
+++ b/apps/desktop/src/styles/settings.css
@@ -2592,6 +2592,28 @@
width: 100%;
}
+/*
+ Plaintext opt-in for endpoints the user typed themselves: the checkbox sits in
+ the row's control column, and the risk copy arrives only while it is on.
+*/
+.settings-network-checkbox {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.settings-network-checkbox input {
+ accent-color: var(--ds-accent);
+}
+
+.settings-network-warning {
+ padding: 10px 12px;
+ border-radius: var(--radius-md);
+ background: color-mix(in srgb, var(--ds-warning) 12%, transparent);
+ color: var(--ds-warning);
+ font-size: var(--text-sm);
+}
+
/* Agent extension state inside a plugin row (spec 16 §11). */
.plugins-agent-extension {
display: flex;
diff --git a/apps/desktop/test/git-clone.test.mjs b/apps/desktop/test/git-clone.test.mjs
index 2e1aeb983..a8047521e 100644
--- a/apps/desktop/test/git-clone.test.mjs
+++ b/apps/desktop/test/git-clone.test.mjs
@@ -7,6 +7,14 @@ import {
cloneGitRepository,
parseGitCloneUrl,
} from "../electron/main/git-clone.ts";
+import { applyUserEndpointPolicyFromAppSettings } from "../electron/main/endpoint-policy.ts";
+
+/** Mirror `settings.networkPolicy` the way the app's settings write does. */
+function setAllowInsecureUserEndpoints(enabled) {
+ applyUserEndpointPolicyFromAppSettings({
+ networkPolicy: { allowInsecureUserEndpoints: enabled },
+ });
+}
test("parseGitCloneUrl accepts https, ssh, and scp remotes", () => {
assert.deepEqual(parseGitCloneUrl("https://github.com/org/pi-desktop.git"), {
@@ -31,15 +39,101 @@ test("parseGitCloneUrl rejects unsafe or incomplete remotes", () => {
assert.equal(parseGitCloneUrl("[email protected]:org/."), null);
});
-test("parseGitCloneUrl rejects private, loopback, and link-local hosts", () => {
- assert.equal(parseGitCloneUrl("https://127.0.0.1/org/repo.git"), null);
- assert.equal(parseGitCloneUrl("http://localhost/org/repo.git"), null);
- assert.equal(parseGitCloneUrl("https://10.0.0.5/org/repo.git"), null);
- assert.equal(parseGitCloneUrl("https://192.168.1.2/org/repo.git"), null);
- assert.equal(parseGitCloneUrl("https://169.254.1.1/org/repo.git"), null);
- assert.equal(parseGitCloneUrl("[email protected]:org/repo.git"), null);
- assert.equal(parseGitCloneUrl("ssh://[email protected]/org/repo.git"), null);
- assert.equal(parseGitCloneUrl("https://[::1]/org/repo.git"), null);
+test("parseGitCloneUrl accepts a remote on the user's own network", () => {
+ // The clone remote is an address the user typed, so a self-hosted GitLab on
+ // the LAN — `192.168.1.5`, `10.0.0.7` — or a local `git daemon` is reachable,
+ // under the same trust rule as every other user-supplied endpoint.
+ assert.deepEqual(parseGitCloneUrl("[email protected]:team/repo.git"), {
+ url: "[email protected]:team/repo.git",
+ name: "repo",
+ });
+ // A plaintext remote on the user's LAN is reachable once they opted in.
+ assert.deepEqual(
+ parseGitCloneUrl("http://10.0.0.7/team/repo.git", {
+ allowInsecureHttp: true,
+ }),
+ {
+ url: "http://10.0.0.7/team/repo.git",
+ name: "repo",
+ },
+ );
+ assert.deepEqual(parseGitCloneUrl("https://127.0.0.1/org/repo.git"), {
+ url: "https://127.0.0.1/org/repo.git",
+ name: "repo",
+ });
+ assert.deepEqual(
+ parseGitCloneUrl("http://localhost/org/repo.git", {
+ allowInsecureHttp: true,
+ }),
+ {
+ url: "http://localhost/org/repo.git",
+ name: "repo",
+ },
+ );
+ assert.deepEqual(parseGitCloneUrl("ssh://[email protected]/org/repo.git"), {
+ url: "ssh://[email protected]/org/repo.git",
+ name: "repo",
+ });
+ assert.deepEqual(parseGitCloneUrl("ssh://[email protected]/org/repo"), {
+ url: "ssh://[email protected]/org/repo",
+ name: "repo",
+ });
+ // Loopback, ULA and link-local literals are the same trust input.
+ assert.deepEqual(parseGitCloneUrl("https://[::1]/org/repo.git")?.name, "repo");
+ assert.deepEqual(parseGitCloneUrl("https://[fd00::1]/org/repo.git")?.name, "repo");
+ assert.deepEqual(parseGitCloneUrl("https://[fe80::1]/org/repo.git")?.name, "repo");
+});
+
+test("parseGitCloneUrl still rejects cloud metadata and non-git URLs", () => {
+ // A metadata service answers with the host's own credentials, and a
+ // documentation or credential-bearing URL is not a remote at all.
+ assert.equal(parseGitCloneUrl("https://169.254.169.254/org/repo.git"), null);
+ assert.equal(parseGitCloneUrl("http://169.254.169.254/latest/meta-data/repo.git"), null);
+ assert.equal(parseGitCloneUrl("[email protected]:org/repo.git"), null);
+ assert.equal(parseGitCloneUrl("https://metadata.google.internal/org/repo.git"), null);
+ assert.equal(parseGitCloneUrl("https://[fd00:ec2::254]/org/repo.git"), null);
+ assert.equal(parseGitCloneUrl("https://[2001:db8::1]/org/repo.git"), null);
+});
+
+test("parseGitCloneUrl refuses plain http and git until the user opts in", () => {
+ // A plaintext hop to a LAN git host carries whatever credentials that host
+ // accepts, so it needs `networkPolicy.allowInsecureUserEndpoints` — the same
+ // gate every other user-supplied endpoint passes. Default stays deny.
+ assert.equal(parseGitCloneUrl("http://10.0.0.7/repo.git"), null);
+ assert.equal(parseGitCloneUrl("git://10.0.0.7/repo"), null);
+ assert.equal(parseGitCloneUrl("http://10.0.0.7/repo.git", {}), null);
+ assert.equal(
+ parseGitCloneUrl("http://10.0.0.7/repo.git", { allowInsecureHttp: false }),
+ null,
+ );
+ assert.deepEqual(
+ parseGitCloneUrl("http://10.0.0.7/repo.git", { allowInsecureHttp: true }),
+ { url: "http://10.0.0.7/repo.git", name: "repo" },
+ );
+ assert.deepEqual(
+ parseGitCloneUrl("git://10.0.0.7/repo", { allowInsecureHttp: true }),
+ { url: "git://10.0.0.7/repo", name: "repo" },
+ );
+});
+
+test("parseGitCloneUrl needs no opt-in for https, ssh, or scp remotes", () => {
+ assert.deepEqual(parseGitCloneUrl("https://192.168.1.5/repo.git"), {
+ url: "https://192.168.1.5/repo.git",
+ name: "repo",
+ });
+ assert.deepEqual(parseGitCloneUrl("[email protected]:team/repo.git"), {
+ url: "[email protected]:team/repo.git",
+ name: "repo",
+ });
+ assert.deepEqual(parseGitCloneUrl("ssh://[email protected]/org/repo.git")?.name, "repo");
+});
+
+test("the insecure flag does not unlock cloud metadata or file URLs", () => {
+ const optedIn = { allowInsecureHttp: true };
+ assert.equal(parseGitCloneUrl("http://169.254.169.254/latest/meta-data/repo.git", optedIn), null);
+ assert.equal(parseGitCloneUrl("https://169.254.169.254/org/repo.git", optedIn), null);
+ assert.equal(parseGitCloneUrl("file:///tmp/repo.git", optedIn), null);
+ assert.equal(parseGitCloneUrl("file://10.0.0.7/repo.git"), null);
});
test("cloneGitRepository refuses an existing destination and path escape", async () => {
@@ -93,14 +187,62 @@ test("cloneGitRepository runs git clone -- url dest", async () => {
}
});
-test("cloneGitRepository rejects a private host before git runs", async () => {
+test("cloneGitRepository runs git for a LAN remote the user typed", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-clone-"));
+ try {
+ let captured;
+ const dest = await cloneGitRepository({
+ url: "[email protected]:team/demo.git",
+ parentPath: root,
+ run: async (_cwd, args) => {
+ captured = { args };
+ mkdirSync(join(root, "demo"));
+ return { code: 0, stderr: "" };
+ },
+ });
+ assert.equal(dest, join(root, "demo"));
+ assert.deepEqual(captured.args, [
+ "clone",
+ "--",
+ "[email protected]:team/demo.git",
+ join(root, "demo"),
+ ]);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("cloneGitRepository rejects a cloud metadata host before git runs", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-clone-"));
+ try {
+ let ran = false;
+ await assert.rejects(
+ () =>
+ cloneGitRepository({
+ url: "https://169.254.169.254/latest/meta-data/repo.git",
+ parentPath: root,
+ run: async () => {
+ ran = true;
+ return { code: 0, stderr: "" };
+ },
+ }),
+ /git repository URL/,
+ );
+ assert.equal(ran, false);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("cloneGitRepository gates a plain http remote on the user's endpoint policy", async () => {
const root = mkdtempSync(join(tmpdir(), "pi-clone-"));
try {
let ran = false;
+ setAllowInsecureUserEndpoints(false);
await assert.rejects(
() =>
cloneGitRepository({
- url: "https://192.168.1.2/team/repo.git",
+ url: "http://10.0.0.7/team/demo.git",
parentPath: root,
run: async () => {
ran = true;
@@ -110,7 +252,20 @@ test("cloneGitRepository rejects a private host before git runs", async () => {
/git repository URL/,
);
assert.equal(ran, false);
+
+ // The opt-in is the main process's, so the same URL clones once it is on.
+ setAllowInsecureUserEndpoints(true);
+ const dest = await cloneGitRepository({
+ url: "http://10.0.0.7/team/demo.git",
+ parentPath: root,
+ run: async () => {
+ mkdirSync(join(root, "demo"));
+ return { code: 0, stderr: "" };
+ },
+ });
+ assert.equal(dest, join(root, "demo"));
} finally {
+ setAllowInsecureUserEndpoints(false);
rmSync(root, { recursive: true, force: true });
}
});
diff --git a/apps/desktop/test/mcp-oauth.test.mjs b/apps/desktop/test/mcp-oauth.test.mjs
index c85407551..a7446670b 100644
--- a/apps/desktop/test/mcp-oauth.test.mjs
+++ b/apps/desktop/test/mcp-oauth.test.mjs
@@ -12,6 +12,12 @@ import {
LOOPBACK_REDIRECT_PORTLESS,
} from "../electron/main/mcp-oauth.ts";
import { UserMcpRuntime } from "../electron/main/user-mcp.ts";
+import { applyUserEndpointPolicyFromAppSettings } from "../electron/main/endpoint-policy.ts";
+
+/** Mirror `settings.networkPolicy` the way the app's settings write does. */
+function setAllowInsecureUserEndpoints(enabled) {
+ applyUserEndpointPolicyFromAppSettings({ networkPolicy: { allowInsecureUserEndpoints: enabled } });
+}
function fakeHost() {
const secrets = new Map();
@@ -659,16 +665,74 @@ test("HTML escaping helper prevents script and attribute injection", () => {
assert.equal(escapeHtml("Tom & Jerry 'cat'"), "Tom &amp; Jerry &#39;cat&#39;");
});
-test("TLS helpers allow HTTPS and loopback HTTP only", () => {
+test("TLS helpers allow HTTPS, loopback HTTP, and plaintext behind the opt-in", () => {
assert.equal(isLoopbackHostname("127.0.0.1"), true);
assert.equal(isLoopbackHostname("localhost"), true);
assert.equal(isLoopbackHostname("evil.test"), false);
assert.equal(assertTlsProtectedUrl("https://auth.example/x", "authorization_endpoint").protocol, "https:");
assert.equal(assertTlsProtectedUrl("http://127.0.0.1:9/x", "token_endpoint").hostname, "127.0.0.1");
+ assert.equal(assertTlsProtectedUrl("http://[::1]:9/x", "token_endpoint").hostname, "[::1]");
+ // Loopback HTTP passes with the opt-in off; a LAN host does not.
+ assert.throws(
+ () => assertTlsProtectedUrl("http://192.168.1.5:8188/token", "token_endpoint"),
+ /must use HTTPS/,
+ );
assert.throws(
() => assertTlsProtectedUrl("http://evil.test/token", "token_endpoint"),
/must use HTTPS/,
);
+ assert.throws(
+ () => assertTlsProtectedUrl("ftp://127.0.0.1/token", "token_endpoint"),
+ /must use HTTPS/,
+ );
+ setAllowInsecureUserEndpoints(true);
+ try {
+ // A plaintext host passes only when it is the host the user typed as their
+ // MCP server (`trustedUrl`): every other URL this guard sees arrives inside
+ // server metadata, so a document must not be able to point the app at an
+ // internal address the user never entered.
+ assert.equal(
+ assertTlsProtectedUrl(
+ "http://192.168.1.5:8188/token",
+ "token_endpoint",
+ "http://192.168.1.5:8188/mcp",
+ ).hostname,
+ "192.168.1.5",
+ );
+ assert.throws(
+ () =>
+ assertTlsProtectedUrl(
+ "http://192.168.1.5:8188/token",
+ "token_endpoint",
+ "http://192.168.1.9:8188/mcp",
+ ),
+ /must use HTTPS/,
+ );
+ assert.throws(
+ () => assertTlsProtectedUrl("http://192.168.1.5:8188/token", "token_endpoint"),
+ /must use HTTPS/,
+ );
+ // Loopback is the RFC 8252 shape and needs no anchor.
+ assert.equal(
+ assertTlsProtectedUrl("http://127.0.0.1:9/x", "token_endpoint").hostname,
+ "127.0.0.1",
+ );
+ // HTTPS is unaffected by the opt-in, and cloud metadata stays refused.
+ assert.equal(
+ assertTlsProtectedUrl("https://auth.example/x", "authorization_endpoint").protocol,
+ "https:",
+ );
+ assert.throws(
+ () => assertTlsProtectedUrl("http://169.254.169.254/latest/meta-data", "token_endpoint"),
+ /must use HTTPS/,
+ );
+ assert.throws(
+ () => assertTlsProtectedUrl("http://metadata.google.internal/token", "token_endpoint"),
+ /must use HTTPS/,
+ );
+ } finally {
+ setAllowInsecureUserEndpoints(false);
+ }
assert.equal(
canReuseDcrClient(
{
@@ -722,6 +786,46 @@ test("McpOAuthManager: rejects non-loopback HTTP authorization servers", async (
/authorization_server must use HTTPS/,
);
});
+test("McpOAuthManager: a plaintext LAN authorization server follows the opt-in", async (t) => {
+ const host = fakeHost();
+ const mockFetch = async (input) => {
+ const url = new URL(typeof input === "string" ? input : input.url);
+ if (url.pathname === "/.well-known/oauth-protected-resource") {
+ return new Response(JSON.stringify({
+ resource: "http://192.168.1.5:8188/mcp",
+ authorization_servers: ["http://192.168.1.5:8188"],
+ }), { status: 200, headers: { "Content-Type": "application/json" } });
+ }
+ if (url.pathname === "/.well-known/oauth-authorization-server") {
+ return new Response(JSON.stringify({
+ issuer: "http://192.168.1.5:8188",
+ authorization_endpoint: "http://192.168.1.5:8188/authorize",
+ token_endpoint: "http://192.168.1.5:8188/token",
+ }), { status: 200, headers: { "Content-Type": "application/json" } });
+ }
+ return new Response(null, { status: 404 });
+ };
+ const manager = new McpOAuthManager({
+ call: host.call,
+ fetchImpl: mockFetch,
+ openExternal: async () => {},
+ });
+ t.after(() => {
+ setAllowInsecureUserEndpoints(false);
+ manager.disposeAll();
+ });
+
+ await assert.rejects(
+ () => manager.discoverMetadata("http://192.168.1.5:8188/mcp"),
+ /authorization_server must use HTTPS/,
+ );
+
+ setAllowInsecureUserEndpoints(true);
+ const metadata = await manager.discoverMetadata("http://192.168.1.5:8188/mcp");
+ assert.equal(metadata.authorizationEndpoint, "http://192.168.1.5:8188/authorize");
+ assert.equal(metadata.tokenEndpoint, "http://192.168.1.5:8188/token");
+});
+
test("McpOAuthManager: unmatched state does not abort login; replay is rejected", async (t) => {
const host = fakeHost();
diff --git a/apps/desktop/test/mcp-registry-catalog.test.mjs b/apps/desktop/test/mcp-registry-catalog.test.mjs
index e8bd971bc..f3f9db420 100644
--- a/apps/desktop/test/mcp-registry-catalog.test.mjs
+++ b/apps/desktop/test/mcp-registry-catalog.test.mjs
@@ -22,6 +22,18 @@ test("fake-IP proxy routes use the session transport without weakening direct pi
assert.match(source, /MAX_SOURCE_RESPONSE_BYTES/);
assert.match(source, /currentNetworkProxy\(\)\.allowFakeIp/);
assert.match(source, /allowFakeIp && addressKind === "benchmark"/);
+ // The source URL is an address the user typed, so only the first hop is judged
+ // for a user-supplied endpoint; every redirect target is third-party content
+ // and keeps the public-only rule.
+ assert.match(source, /hop === 0 \? "user" : "third-party"/);
+ assert.match(source, /const userSupplied = origin === "user"/);
+ assert.match(
+ source,
+ /isSafeMarketSourceUrl\(url, \{ allowInsecureHttp: allowInsecureUserEndpointsEnabled\(\) \}\)/,
+ );
+ assert.match(source, /: isSafePublicHttpsUrl\(url\)/);
+ assert.match(source, /isAcceptableUserEndpointAddress\(address\.address, addressKind, route\)/);
+ assert.match(source, /: isAcceptableResolvedAddress\(addressKind, route\)/);
});
test("market source responses and caches are bounded", () => {
diff --git a/apps/desktop/test/public-https-fetch-route.test.mjs b/apps/desktop/test/public-https-fetch-route.test.mjs
index a6d3c3321..557c2214c 100644
--- a/apps/desktop/test/public-https-fetch-route.test.mjs
+++ b/apps/desktop/test/public-https-fetch-route.test.mjs
@@ -251,3 +251,54 @@ test("the market catalog client asks the session that carries its fetch", async
assert.match(source, /fetchImpl: \(url, init\) => net\.fetch\(url, init\)/);
assert.match(source, /routeImpl: \(url\) => session\.defaultSession\.resolveProxy\(url\)/);
});
+
+test("a user-supplied endpoint reaches its own LAN on any route", async () => {
+ // `benchmark` is the only class the route decides for a third-party hop, and
+ // it stays that way. A user-supplied endpoint is a different trust input: the
+ // address is theirs, so a private one is dialed whether the session goes
+ // direct or through a proxy.
+ for (const route of ["DIRECT", PROXIED]) {
+ const client = clientFor({ route, address: "10.0.0.8" });
+ assert.equal(
+ await client.request("https://nas.local/catalog.json", "text", "user"),
+ "# skill\n",
+ );
+ }
+
+ // The same address on the default origin keeps the strict verdict, whichever
+ // route carries it.
+ for (const route of ["DIRECT", PROXIED]) {
+ const client = clientFor({
+ route,
+ address: "10.0.0.8",
+ fetchImpl: async () => {
+ throw new Error("a refused request must never reach the network");
+ },
+ });
+ await assert.rejects(
+ () => client.assertPublicUrl("https://nas.example/catalog.json"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError &&
+ error.reason === "non-public-address" &&
+ error.addressKind === "private",
+ );
+ }
+
+ // A fake-IP answer is the proxy's own placeholder rather than a service the
+ // user runs, so it is refused on the user's own endpoint too unless the route
+ // says this app dials a proxy — the same rule the third-party hop has.
+ const fakeIp = clientFor({
+ route: "DIRECT",
+ address: FAKE_IP,
+ fetchImpl: async () => {
+ throw new Error("a refused request must never reach the network");
+ },
+ });
+ await assert.rejects(
+ () => fakeIp.assertPublicUrl("https://nas.local/catalog.json", "user"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError &&
+ error.reason === "non-public-address" &&
+ error.addressKind === "benchmark",
+ );
+});
diff --git a/apps/desktop/test/public-https-fetch.test.mjs b/apps/desktop/test/public-https-fetch.test.mjs
index f9ba5f0f9..0d9608660 100644
--- a/apps/desktop/test/public-https-fetch.test.mjs
+++ b/apps/desktop/test/public-https-fetch.test.mjs
@@ -119,3 +119,125 @@ test("a syntactic URL refusal carries the same code", async () => {
(error) => error.errorCode === ErrorCodes.NETWORK_POLICY_BLOCKED,
);
});
+
+test("a user-supplied endpoint may resolve to the machine or the LAN", async () => {
+ // The address belongs to whoever typed the endpoint in, so loopback, RFC1918
+ // and link-local are reachable there. The same address on the default
+ // (third-party) origin stays refused, which is the behaviour nothing here
+ // changes.
+ const client = createPublicHttpsClient({
+ fetchImpl: async () => jsonResponse(200, { ok: true }),
+ lookupImpl: async () => [{ address: "10.0.0.8" }],
+ });
+ await assert.rejects(
+ () => client.request("https://nas.example/catalog.json", "json"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError &&
+ error.reason === "non-public-address" &&
+ error.addressKind === "private",
+ );
+ assert.deepEqual(await client.request("https://nas.example/catalog.json", "json", "user"), {
+ ok: true,
+ });
+ await client.assertPublicUrl("https://nas.local:8443/catalog.json", "user");
+
+ const loopback = createPublicHttpsClient({
+ fetchImpl: async () => jsonResponse(200, { ok: true }),
+ lookupImpl: async () => [{ address: "127.0.0.1" }],
+ });
+ await loopback.assertPublicUrl("https://local.example/catalog.json", "user");
+});
+
+test("a user-supplied endpoint still may not name cloud metadata", async () => {
+ // A metadata service answers with the host's own credentials, so no settings
+ // field may spell one — not even the field the user fills in themselves.
+ const byHost = createPublicHttpsClient({
+ fetchImpl: async () => {
+ throw new Error("a refused request must never reach the network");
+ },
+ lookupImpl: async () => [{ address: "10.0.0.8" }],
+ });
+ await assert.rejects(
+ () => byHost.assertPublicUrl("https://169.254.169.254/latest/meta-data", "user"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError && error.reason === "url-syntax",
+ );
+ await assert.rejects(
+ () => byHost.assertPublicUrl("https://metadata.google.internal/computeMetadata", "user"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError && error.reason === "url-syntax",
+ );
+
+ // …and not by resolution either: the address the user's own hostname answers
+ // with is still judged, and a metadata address fails that judgement.
+ const byAddress = createPublicHttpsClient({
+ fetchImpl: async () => {
+ throw new Error("a refused request must never reach the network");
+ },
+ lookupImpl: async () => [{ address: "169.254.169.254" }],
+ });
+ await assert.rejects(
+ () => byAddress.assertPublicUrl("https://internal.example/catalog.json", "user"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError &&
+ error.reason === "non-public-address" &&
+ error.address === "169.254.169.254" &&
+ error.addressKind === "link-local",
+ );
+});
+
+test("plaintext needs the stored opt-in, and only for a user-supplied endpoint", async () => {
+ const strict = createPublicHttpsClient({
+ fetchImpl: async () => jsonResponse(200, "catalog"),
+ lookupImpl: async () => [{ address: "192.168.1.5" }],
+ });
+ await assert.rejects(
+ () => strict.request("http://192.168.1.5:8080/catalog.json", "text", "user"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError &&
+ error.reason === "url-syntax" &&
+ error.errorCode === ErrorCodes.NETWORK_POLICY_BLOCKED,
+ );
+
+ const permissive = createPublicHttpsClient({
+ fetchImpl: async () => jsonResponse(200, "catalog"),
+ lookupImpl: async () => [{ address: "192.168.1.5" }],
+ allowInsecureUserEndpoints: true,
+ });
+ assert.equal(
+ await permissive.request("http://192.168.1.5:8080/catalog.json", "text", "user"),
+ "catalog",
+ );
+ // The opt-in is exactly that: it buys the plaintext hop to the user's own
+ // endpoint, and nothing on the third-party origin.
+ await assert.rejects(
+ () => permissive.request("http://192.168.1.5:8080/catalog.json", "text"),
+ (error) => error instanceof PublicNetworkPolicyError && error.reason === "url-syntax",
+ );
+});
+
+test("only the first hop is the user's: a redirect is judged as third-party", async () => {
+ const seen = [];
+ const client = createPublicHttpsClient({
+ fetchImpl: async (url) => {
+ seen.push(url);
+ if (url === "https://start.example/start.json") {
+ return jsonResponse(302, "", "https://internal.example/next.json");
+ }
+ return jsonResponse(200, { ok: true });
+ },
+ lookupImpl: async () => [{ address: "127.0.0.1" }],
+ });
+ // The first hop is the endpoint the user typed, so its loopback answer is
+ // theirs; the redirect target is an address the app learned from that
+ // endpoint's answer, so the same answer is a refusal there.
+ await assert.rejects(
+ () => client.request("https://start.example/start.json", "json", "user"),
+ (error) =>
+ error instanceof PublicNetworkPolicyError &&
+ error.reason === "non-public-address" &&
+ error.host === "internal.example" &&
+ error.addressKind === "loopback",
+ );
+ assert.deepEqual(seen, ["https://start.example/start.json"]);
+});
diff --git a/apps/desktop/test/skill-market-policy-refusal.test.mjs b/apps/desktop/test/skill-market-policy-refusal.test.mjs
index 97c2dc46c..2f243937a 100644
--- a/apps/desktop/test/skill-market-policy-refusal.test.mjs
+++ b/apps/desktop/test/skill-market-policy-refusal.test.mjs
@@ -233,11 +233,49 @@ test("all seven built-in sources stay refused under a TUN resolver, never admitt
* user their catalog source is bad when the thing to change is their proxy mode.
*/
-/** The market's verdict for one literal, through the real client and aggregator. */
+/**
+ * The market's verdict for one literal, through the real client and aggregator.
+ *
+ * The first hop of a scan is the source the user added, so its address is judged
+ * for a user-supplied endpoint: a loopback or RFC1918 answer there is the user's
+ * own service (or their own split-horizon resolver) and the request proceeds.
+ */
async function marketKindForAddress(address) {
const client = createPublicHttpsClient({
fetchImpl: async () => {
- throw new Error("a refused request must never reach the network");
+ throw new Error("reached the transport");
+ },
+ lookupImpl: async () => [{ address }],
+ });
+ return createSkillMarketAggregator(client.request).search("", [composio]);
+}
+
+/**
+ * The same verdict for an address a hop the app did *not* receive from the user
+ * answers with — here a redirect target.
+ *
+ * Only the first hop is the user's own source; every hop after a redirect keeps
+ * the public-only policy, because that is the address an attacker who controls
+ * the source can aim. Cloud metadata and a fake-IP are refused on both.
+ */
+async function marketKindForRedirectTargetAddress(address) {
+ const client = createPublicHttpsClient({
+ fetchImpl: async (url) => {
+ if (url.startsWith(`https://${SCAN_HOST}/`)) {
+ return {
+ status: 302,
+ ok: false,
+ headers: {
+ get: (name) =>
+ name.toLowerCase() === "location"
+ ? "https://internal.example/catalog.json"
+ : null,
+ },
+ json: async () => ({}),
+ text: async () => "",
+ };
+ }
+ throw new Error("reached the transport");
},
lookupImpl: async () => [{ address }],
});
@@ -252,11 +290,27 @@ test("a proxy fake-IP is its own cause, not the same finding as a private target
(await marketKindForAddress("198.19.255.254")).failureKinds[composio.name],
"fake-ip",
);
- // A real private or loopback target is a different finding, with different
- // advice: that one is about the destination, not about the proxy.
- assert.equal((await marketKindForAddress("127.0.0.1")).failureKinds[composio.name], "policy");
- assert.equal((await marketKindForAddress("10.1.2.3")).failureKinds[composio.name], "policy");
- assert.equal((await marketKindForAddress("192.168.1.10")).failureKinds[composio.name], "policy");
+ // A private or loopback answer is no longer a refusal on the source the user
+ // added: the scan's first hop is `api.github.com` for that source, so those
+ // addresses are the user's own service or their own split-horizon resolver and
+ // the request proceeds — the stub transport is what fails it, not the guard.
+ for (const address of ["127.0.0.1", "10.1.2.3", "192.168.1.10"]) {
+ assert.equal(
+ (await marketKindForAddress(address)).failureKinds[composio.name],
+ "network",
+ `expected ${address} to reach the transport on the user's own source`,
+ );
+ }
+ // The same answer on a hop the app learned from someone else — a redirect
+ // target — is a different finding, with different advice: that one is about
+ // the destination, not about the proxy.
+ for (const address of ["127.0.0.1", "10.1.2.3"]) {
+ assert.equal(
+ (await marketKindForRedirectTargetAddress(address)).failureKinds[composio.name],
+ "policy",
+ `expected ${address} to stay refused on a redirect target`,
+ );
+ }
});
test("the fake-IP cause never admits the request", async () => {
@@ -297,19 +351,28 @@ test("the refusal names the host and the address, not only the source label", as
addressKind: "benchmark",
route: "unknown",
});
- const privateTarget = await marketKindForAddress("10.1.2.3");
- assert.equal(privateTarget.failureDetails[composio.name].address, "10.1.2.3");
- assert.equal(privateTarget.failureDetails[composio.name].addressKind, "private");
+ // A hop that came from someone else carries the same fields, and the class is
+ // what separates a proxy artifact from a target.
+ const redirectedTarget = await marketKindForRedirectTargetAddress("10.1.2.3");
+ assert.equal(redirectedTarget.failureDetails[composio.name].address, "10.1.2.3");
+ assert.equal(redirectedTarget.failureDetails[composio.name].addressKind, "private");
+ assert.equal(redirectedTarget.failureDetails[composio.name].host, "internal.example");
+ assert.equal(
+ redirectedTarget.failureDetails[composio.name].reason,
+ "non-public-address",
+ );
});
test("a resolver that answered nothing is not a fake-IP and not a verdict", async () => {
// The three cases the lead asks to keep apart, asserted side by side so a
// future refactor cannot merge two of them again.
const judgedFake = await marketKindForAddress("198.18.0.1");
- assert.equal(judgedFake.failureKinds[composio.name], "fake-ip");
-
- const judgedPrivate = await marketKindForAddress("10.1.2.3");
+ const judgedPrivate = await marketKindForRedirectTargetAddress("10.1.2.3");
assert.equal(judgedPrivate.failureKinds[composio.name], "policy");
+ // …and a private answer on the source the user added is not a verdict at all:
+ // that hop is theirs, so the request proceeds (the stub transport fails it).
+ const userSource = await marketKindForAddress("10.1.2.3");
+ assert.equal(userSource.failureKinds[composio.name], "network");
const silent = createPublicHttpsClient({
fetchImpl: async () => {
@@ -320,12 +383,15 @@ test("a resolver that answered nothing is not a fake-IP and not a verdict", asyn
const unanswered = await createSkillMarketAggregator(silent.request).search("", [composio]);
assert.equal(unanswered.failureKinds[composio.name], "unresolved");
+ // A source the syntactic guard refuses never reaches the transport at all, and
+ // it is still a verdict about the URL: a cloud metadata host names the
+ // machine's own credentials, not a catalog the user runs.
const syntactic = createSkillMarketAggregator(async () => {
throw new Error("a syntactically refused source is never requested");
});
const refused = await syntactic.search("", [
- { id: "x", name: "x/private", url: "https://10.0.0.8/catalog.json" },
+ { id: "x", name: "x/metadata", url: "https://169.254.169.254/catalog.json" },
]);
- assert.equal(refused.failureKinds["x/private"], "policy");
- assert.equal(refused.failureDetails["x/private"].reason, "url-syntax");
+ assert.equal(refused.failureKinds["x/metadata"], "policy");
+ assert.equal(refused.failureDetails["x/metadata"].reason, "url-syntax");
});
diff --git a/apps/desktop/test/skill-market-scan.test.mjs b/apps/desktop/test/skill-market-scan.test.mjs
index cf5b48187..38ecc1142 100644
--- a/apps/desktop/test/skill-market-scan.test.mjs
+++ b/apps/desktop/test/skill-market-scan.test.mjs
@@ -82,17 +82,49 @@ test("jsDelivr listing inlines adjacent markdown only", async () => {
});
test("unsafe source URLs fail closed without a request", async () => {
+ // The source URL is an address the user typed, so loopback and the LAN are
+ // reachable now; the classes that name no service at all — and a cloud
+ // metadata host, which answers with the machine's own credentials — are still
+ // refused before anything leaves the process.
let called = 0;
const aggregator = createSkillMarketAggregator(async () => {
called += 1;
throw new Error("should not fetch");
});
const result = await aggregator.search("", [
- { id: "local", name: "local", url: "https://127.0.0.1/catalog.json" },
+ { id: "metadata", name: "metadata", url: "https://169.254.169.254/catalog.json" },
+ { id: "local-file", name: "local-file", url: "file:///etc/passwd" },
+ { id: "unresolvable", name: "unresolvable", url: "not a url" },
]);
assert.equal(called, 0);
assert.deepEqual(result.entries, []);
- assert.deepEqual(result.failedSources, ["local"]);
+ assert.deepEqual(result.failedSources, ["metadata", "local-file", "unresolvable"]);
+ for (const name of result.failedSources) {
+ assert.equal(result.failureKinds[name], "policy");
+ assert.equal(result.failureDetails[name].reason, "url-syntax");
+ }
+});
+
+test("a source the user runs on the LAN is requested instead of refused", async () => {
+ // The user typed this address, so a catalog on their own machine or LAN is
+ // fetched; the public-only policy still governs every URL that arrives on a
+ // redirect hop or inside a catalog body, which the case above does not reach.
+ const seen = [];
+ const aggregator = createSkillMarketAggregator(async (url) => {
+ seen.push(url);
+ return { skills: [] };
+ });
+ const result = await aggregator.search("", [
+ { id: "lan", name: "lan", url: "https://192.168.1.5/catalog.json" },
+ { id: "loopback", name: "loopback", url: "https://127.0.0.1/catalog.json" },
+ ]);
+ assert.deepEqual(seen, [
+ "https://192.168.1.5/catalog.json",
+ "https://127.0.0.1/catalog.json",
+ ]);
+ assert.deepEqual(result.entries, []);
+ assert.deepEqual(result.failedSources, []);
+ assert.deepEqual(result.failureKinds, {});
});
test("main-process aggregator routes through the public-network client", async () => {
@@ -111,7 +143,14 @@ test("main-process aggregator routes through the public-network client", async (
src,
/routeImpl: \(url\) => session\.defaultSession\.resolveProxy\(url\)/,
);
- assert.match(src, /createSkillMarketAggregator\(client\.request\)/);
+ // One injected client, and the same policy object that client was built with:
+ // the aggregator's source filter must accept the LAN source the client would
+ // then dial, and both read the opt-in from the stored settings.
+ assert.match(src, /createSkillMarketAggregator\(client\.request, \{/);
+ assert.match(
+ src,
+ /allowInsecureUserEndpoints: \(\) => allowInsecureUserEndpointsEnabled\(\)/,
+ );
assert.doesNotMatch(src, /node:https|node:http|axios|got\(/);
});
@@ -133,10 +172,18 @@ test("a failed source reports whether the policy or the transport refused it", a
const result = await aggregator.search("", [
{ id: "blocked", name: "blocked/repo", url: "https://blocked.example/catalog.json" },
{ id: "down", name: "down/repo", url: "https://down.example/catalog.json" },
- { id: "local", name: "local", url: "https://127.0.0.1/catalog.json" },
+ {
+ id: "metadata",
+ name: "metadata",
+ url: "https://169.254.169.254/catalog.json",
+ },
]);
assert.deepEqual(result.entries, []);
- assert.deepEqual([...result.failedSources].sort(), ["blocked/repo", "down/repo", "local"]);
+ assert.deepEqual([...result.failedSources].sort(), [
+ "blocked/repo",
+ "down/repo",
+ "metadata",
+ ]);
// Issue #419: a policy refusal must not be indistinguishable from a dead host,
// from a source that never left the syntactic guard, or from a fake-IP the
// local proxy invented. The address here is the proxy's placeholder for
@@ -144,7 +191,7 @@ test("a failed source reports whether the policy or the transport refused it", a
assert.deepEqual(result.failureKinds, {
"blocked/repo": "fake-ip",
"down/repo": "network",
- local: "policy",
+ metadata: "policy",
});
// …and each name carries what it was about, not just which bucket it landed
// in. A transport failure answers a 502 with a bare host.
@@ -155,9 +202,9 @@ test("a failed source reports whether the policy or the transport refused it", a
address: "198.18.0.4",
addressKind: "benchmark",
});
- assert.deepEqual(result.failureDetails.local, {
+ assert.deepEqual(result.failureDetails.metadata, {
kind: "policy",
- host: "127.0.0.1",
+ host: "169.254.169.254",
reason: "url-syntax",
});
assert.deepEqual(result.failureDetails["down/repo"], { kind: "network", host: "down.example" });
@@ -168,9 +215,9 @@ test("a repeated display name keeps the refusal, and a hostile name stays own",
throw new Error("responded 502");
});
const result = await aggregator.search("", [
- { id: "a", name: "same", url: "https://127.0.0.1/catalog.json" },
+ { id: "a", name: "same", url: "https://169.254.169.254/catalog.json" },
{ id: "b", name: "same", url: "https://down.example/catalog.json" },
- { id: "c", name: "__proto__", url: "https://127.0.0.1/catalog.json" },
+ { id: "c", name: "__proto__", url: "https://169.254.169.254/catalog.json" },
]);
// `failedSources` cannot tell the two "same" sources apart, so the kind that
// is worth surfacing (the refusal) must survive the merge.
diff --git a/crates/host-core/src/network_proxy.rs b/crates/host-core/src/network_proxy.rs
index f699be608..2d34995b4 100644
--- a/crates/host-core/src/network_proxy.rs
+++ b/crates/host-core/src/network_proxy.rs
@@ -16,7 +16,10 @@ pub enum ProxyMode {
static MARKET_PROXY: RwLock<ProxyMode> = RwLock::new(ProxyMode::System);
-const DEFAULT_BYPASS: &str = "localhost,127.0.0.1,::1,<local>";
+/// Mirrors `DEFAULT_NETWORK_PROXY_BYPASS` in `packages/shared`: loopback plus
+/// the private ranges a user's own LAN devices live in, so a custom proxy never
+/// swallows a local model server, NAS or MCP endpoint.
+const DEFAULT_BYPASS: &str = "localhost,127.0.0.1,::1,<local>,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16";
pub fn apply_from_settings(value: Option<&Value>) {
let next = proxy_from_settings(value);
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 9d5b5d9bc..e2bd624e3 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -727,6 +727,25 @@ fn validate_settings_value(value: &Value) -> Result<(), JsonRpcError> {
let Some(object) = value.as_object() else {
return Ok(());
};
+ if let Some(policy) = object.get("networkPolicy").filter(|v| !v.is_null()) {
+ let Some(policy) = policy.as_object() else {
+ return Err(rpc_err(
+ 1002,
+ "networkPolicy must be an object",
+ "INVALID_PARAMS",
+ ));
+ };
+ if policy
+ .get("allowInsecureUserEndpoints")
+ .is_some_and(|flag| !flag.is_boolean())
+ {
+ return Err(rpc_err(
+ 1002,
+ "allowInsecureUserEndpoints must be a boolean",
+ "INVALID_PARAMS",
+ ));
+ }
+ }
if let Some(binding) = object.get("imageGeneration").filter(|v| !v.is_null()) {
for (key, max) in [("providerId", 128), ("modelId", 256)] {
if !binding
diff --git a/docs/adr/0304-user-supplied-endpoint-trust.md b/docs/adr/0304-user-supplied-endpoint-trust.md
new file mode 100644
index 000000000..8cc5466c5
--- /dev/null
+++ b/docs/adr/0304-user-supplied-endpoint-trust.md
@@ -0,0 +1,98 @@
+# ADR 0304: Trust the network endpoints the user enters themselves
+
+- Status: Accepted for implementation
+- Date: 2026-09-22
+- Related: ADR 0142, ADR 0177, ADR 0243, ADR 0245, ADR 0247, ADR 0257, ADR 0272, ADR 0300
+
+## Context
+
+ADR 0243, ADR 0245, ADR 0247 and ADR 0272 built one public-network boundary and
+applied it to every request the app makes on its own behalf: a market source, a
+redirect hop, a git remote, a resolved address. That boundary is load-bearing. A
+catalog body the app did not receive from the user must not be able to point the
+main process at the machine's own network.
+
+The same boundary also fell on addresses the user typed into a settings field: a
+self-hosted GitLab at `192.168.1.5`, a LAN ComfyUI at
+`http://192.168.1.5:8188`, an MCP OAuth authorization server on a private
+address, a catalog served by a machine in the same room. Those are not
+third-party content. The user already knows that machine, and refusing the
+address did not remove the request — it moved the same work into curl, a
+browser, or an application-external git remote, while the app's own copy of the
+feature could not be used at all.
+
+Three surfaces had already made that distinction. ADR 0142 accepts a
+non-loopback HTTP MCP endpoint with an explicit risk disclosure; ADR 0300
+accepts a WebDAV endpoint on a private address under an acknowledgement; ADR
+0257 lets a declared `net.domains` entry name a loopback or private host. Git
+clone, market sources, MCP OAuth and generated-image download had not, and the
+result was one boundary with two different meanings in it.
+
+## Decision
+
+1. A **user-supplied endpoint** may reach loopback, RFC1918, CGNAT, link-local,
+ ULA, site-local and `.local` addresses, as well as any public address. It is
+ an address the person typed: a model base URL, an MCP server, a market source
+ URL, a git remote, a generated-image URL from a provider they configured.
+2. Plain `http` for such an endpoint requires the stored opt-in
+ `settings.networkPolicy.allowInsecureUserEndpoints` (default off) — the shape
+ ADR 0300 uses for WebDAV, and the reason ADR 0142 discloses the risk. `https`
+ to a private host needs no opt-in: the transport is protected and the address
+ is the user's own choice.
+3. **Third-party content keeps the strict policy.** A registry record, a market
+ catalog body, a document URL inside a catalog, and every HTTP redirect target
+ are still judged by the public-only rule, with the resolved address pinned to
+ the connection. The shared client therefore takes the origin of each hop: the
+ first hop of a request the user started may be `user`, and every hop after a
+ redirect is `third-party` unconditionally.
+4. An OAuth authorization server reached over plaintext is trusted only when it
+ sits on the same host as the MCP server the user typed. Every other endpoint
+ that flow reads — `WWW-Authenticate`, a protected-resource document, an
+ authorization-server document, a stored token endpoint — arrives inside
+ server metadata, so a server must not be able to send the app to a plaintext
+ internal address the user never entered. Loopback stays allowed (RFC 8252).
+5. `unspecified`, `multicast`, `reserved`, `documentation`, `invalid` and cloud
+ metadata stay refused on **every** input, including a user-supplied one. None
+ of them names a service a user could mean, and the metadata services answer
+ with the host's own credentials.
+6. The default proxy bypass list gains the private ranges, so a configured proxy
+ does not swallow the user's own LAN services.
+7. The syntactic judgement stays in `packages/shared`, and the authoritative one
+ stays at the connection: a DNS answer outside the policy is refused before
+ the socket, and an acceptable address is pinned to it (ADR 0245, ADR 0272).
+
+## Consequences
+
+- A model endpoint, an MCP server, a market source, a git remote and a
+ generated-image URL can all point at the user's own machine or LAN from inside
+ the app, instead of only from a shell next to it.
+- The main process gains an SSRF-shaped capability whose targets the user typed
+ on purpose. The residual risk is the settings field the user did *not* type —
+ a source that redirects, a catalog body, a registry record — and those paths
+ stay on the public-only policy. Refusals still name the address class, so a
+ proxy fake-IP artifact is told apart from a real private target (issue #419).
+- A plaintext hop to a LAN service is opt-in and warned about; whatever
+ credentials that endpoint accepts travel unencrypted across the local network.
+- ADR 0247's consequence — "clone a private-host repository with an
+ application-external git remote" — no longer applies. The decision items in
+ ADR 0243, 0245 and 0247 that cover *user-supplied* URLs are amended here; their
+ rules for third-party content are unchanged and stay in force.
+
+## Rejected alternatives
+
+- **Keep refusing LAN addresses for user-supplied endpoints, and document the
+ workaround.** Rejected: the workaround is the same request from a different
+ process, so the refusal buys no security and costs the feature.
+- **Trust every address everywhere, including third-party content.** Rejected:
+ that is the SSRF path the guard exists for — a catalog body, a registry record
+ or a redirect is content the app received from someone else, and DNS rebinding
+ makes a pre-flight check alone insufficient (ADR 0245).
+- **Permit cloud metadata as well, since the user typed it.** Rejected: the
+ metadata service returns instance credentials to anything that asks, it is
+ never a service a user runs, and an address that appears in a settings field
+ is far more likely to be an injected payload than a deliberate choice.
+- **Per-source acknowledgement stored with the source list.** Rejected: the
+ source list lives in renderer storage, where a flag is exactly as trustworthy
+ as the URL next to it, so it would add UI without adding a boundary. The
+ acknowledgement belongs in host-owned settings, where `settings.set` is the
+ single writer.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 3625e65f7..affd17920 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -333,6 +333,7 @@ Each ADR includes:
| 0301 | [Explicit append-only WebDAV compatibility mode](0301-explicit-append-only-webdav-compatibility-mode.md) | Accepted for implementation |
| 0302 | [A failed compaction keeps the recent window, and an oversized summary is chunked](0302-compaction-fallback-recent-window-and-chunked-summary.md) | Accepted for implementation (issue #827; amends ADR 0049 / ADR 0282) |
| 0303 | [A skill package carries resources far above the document cap](0303-skill-package-resource-limits.md) | Accepted for implementation (amends ADR 0300) |
+| 0304 | [Trust the network endpoints the user enters themselves](0304-user-supplied-endpoint-trust.md) | Accepted for implementation (amends ADR 0243 / 0245 / 0247; follows ADR 0142 / 0257 / 0300) |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
| provider-display-order | [Provider display order](provider-display-order.md) | Accepted |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed |
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 1a244fb3e..be09cb0b7 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -66,7 +66,7 @@ registered; reserved codes in §3.7 remain intentionally absent from
| `APPROVAL_STALE` | no | RACP: the approval was already settled or belongs to an older turn |
| `PAYLOAD_TOO_LARGE` | no | RACP: a frame exceeded the negotiated size bound |
| `TIMEOUT` | yes | generic timeout |
-| `NETWORK_POLICY_BLOCKED` | no | the main-process public-network guard refused a fetch because it *judged* the target: the URL failed the syntactic public-HTTPS check, or the local DNS lookup returned an address the policy classifies as non-public — including a fake-IP placeholder a local proxy invented (ADR 0243). A desktop-only code; a refusal is a verdict, so retrying cannot succeed until the address changes. A resolver that returned no answer at all is `NETWORK_RESOLVE_FAILED` instead (issue #419). |
+| `NETWORK_POLICY_BLOCKED` | no | the main-process public-network guard refused a fetch because it *judged* the target: the URL failed the syntactic public-HTTPS check, or the local DNS lookup returned an address the policy classifies as non-public — including a fake-IP placeholder a local proxy invented (ADR 0243). A desktop-only code; a refusal is a verdict, so retrying cannot succeed until the address changes. A resolver that returned no answer at all is `NETWORK_RESOLVE_FAILED` instead (issue #419). Since ADR 0304 an endpoint the user typed themselves may resolve to their own loopback or LAN, so this code now reports a first hop only for the classes that name no service at all (cloud metadata, unspecified, multicast, reserved) or for a third-party hop — a redirect target, a catalog body, a registry record. |
| `NETWORK_RESOLVE_FAILED` | yes | the main-process public-network guard could not classify the target host: the local DNS lookup returned no answer, or threw before returning one. The request is refused exactly as a policy refusal is, but no address was judged, so no page or log may report it as an address-check decision. Distinct from `NETWORK_ERROR`, which is a failure of the request itself. Retriable: a resolver or proxy that starts answering the same host makes the same request succeed (ADR 0243, issue #419). |
| `HOST_SHUTTING_DOWN` | yes | the host received EOF and is draining; the call was refused rather than started |
| `RATE_LIMITED` | yes | a per-caller host budget (plugin session import, batch operations) was exceeded inside its window |
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 279e15835..6142e7eb9 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -130,15 +130,22 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
`net.fetch`, and the in-app browser). Workspace Bash and the system
browser used for OAuth are not rewritten.
- Custom shows a Proxy URL field (`socks5://127.0.0.1:1080` /
- `http://127.0.0.1:7890`, including `user:pass@` userinfo), a Bypass
- list defaulting to `localhost,127.0.0.1,::1,<local>` so loopback MCP
- and local models stay direct, and a Test action that issues one
- Chromium fetch through the draft proxy. Credentialed URLs are applied
- to Chromium through a loopback SOCKS5 relay (issue #490). The URL is
- validated on blur; invalid schemes are rejected.
+ `http://127.0.0.1:7890`, including `user:pass@` userinfo), a Bypass list
+ defaulting to
+ `localhost,127.0.0.1,::1,<local>,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16`
+ so loopback MCP, local models and every LAN service stay direct, and a Test
+ action that issues one Chromium fetch through the draft proxy. Credentialed
+ URLs are applied to Chromium through a loopback SOCKS5 relay (issue #490).
+ The URL is validated on blur; invalid schemes are rejected.
- The selection persists as optional `AppSettings.networkProxy`
(`mode` / `url` / `bypass`). Absent means System. No host protocol or
storage schema version bump (D340 / ADR 0177).
+ - **Plaintext HTTP for your own endpoints**: one checkbox persisting as
+ `AppSettings.networkPolicy.allowInsecureUserEndpoints` (default off). It
+ lets an endpoint you typed yourself — a model base URL, an MCP server, a
+ market source — use `http`. The warning states that the connection is not
+ encrypted and that whatever that endpoint accepts can be read on the same
+ network segment. `https` to a LAN host needs no checkbox (ADR 0304).
- Platform-specific **Close behavior** remains in General because it changes
application-window behavior rather than agent behavior.
- File-open target, menu-bar behavior, and bottom-panel behavior are not
diff --git a/docs/spec/05-security/01-security.md b/docs/spec/05-security/01-security.md
index 87013c18e..697458ae3 100644
--- a/docs/spec/05-security/01-security.md
+++ b/docs/spec/05-security/01-security.md
@@ -114,6 +114,12 @@ transparent router/TUN deployment. Install writes markdown only through
`skills.create`. The host document cap remains 128 KiB after sibling markdown
is inlined.
+A source URL the user typed is judged by ADR 0304 instead: it may be a loopback
+or LAN catalog, and plain `http` to it needs the stored
+`networkPolicy.allowInsecureUserEndpoints` opt-in. Every document URL that
+arrives *inside* a catalog, and every redirect target, keeps the public-only
+policy above.
+
## 4.2 MCP market egress
The MCP market accepts only credentials-free public HTTPS sources and catalog
@@ -134,6 +140,12 @@ redirects do not forward caller headers.
Manual user-owned MCP configuration remains covered by ADR 0142 and may use
explicit local/LAN endpoints; the market path does not widen that policy.
+
+A market source URL the user typed is judged by ADR 0304 as well: it may be a
+loopback or LAN endpoint, with plain `http` behind
+`networkPolicy.allowInsecureUserEndpoints`. Everything a source returns —
+registry records, catalog bodies, redirect targets — keeps the public-only
+policy above.
## 4.3 Portable configuration sync
WebDAV sync is a host-core network boundary. The renderer and Agent Runtime
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 9d95e4860..4a7ba3edf 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13182,12 +13182,12 @@ plugin-form fixtures in an isolated temporary directory at runtime.
`git-clone.test.mjs`, `sidebar-preferences.test.mjs`); full UI scenario Draft
(run only in a capable environment when this surface changes)
-#### E2E-CLONE-public-hostname-rejects-private
+#### E2E-CLONE-accepts-a-lan-remote-and-rejects-metadata
- **Preconditions**: The home project switcher Clone git project action is available.
-- **Steps**: 1) Enter `https://127.0.0.1/org/repo.git`, `http://localhost/org/repo.git`, `https://10.0.0.5/org/repo.git`, and `[email protected]:org/repo.git`. 2) Enter `https://github.com/org/repo.git` and `[email protected]:org/repo.git`.
-- **Expected**: Private, loopback, and link-local remotes are rejected before `git clone` runs. Public GitHub HTTPS and SSH remotes still parse to a folder name. `file:` and password-bearing URLs remain rejected.
-- **Specs linked**: `04-ux/01-ui-ia.md`, ADR 0247, D416
+- **Steps**: 1) Enter `https://192.168.1.5/org/repo.git`, `http://10.0.0.7/org/repo.git`, and `[email protected]:org/repo.git`. 2) Enter `https://169.254.169.254/org/repo.git` and `https://metadata.google.internal/org/repo.git`. 3) Enter `https://github.com/org/repo.git` and `[email protected]:org/repo.git`.
+- **Expected**: A LAN or loopback remote the user typed is accepted and parses to a folder name, because the remote is the user's own address. Cloud metadata hosts stay rejected, as do `file:` and password-bearing URLs, before `git clone` runs. Public GitHub HTTPS and SSH remotes still parse.
+- **Specs linked**: `04-ux/01-ui-ia.md`, ADR 0247, ADR 0304, D416
- **Acceptance**: Security, D (workspace)
- **Milestone**: M5
- **Status**: Unit-covered (`apps/desktop/test/git-clone.test.mjs`)
@@ -13630,27 +13630,33 @@ plugin-form fixtures in an isolated temporary directory at runtime.
| ID | Scenario | Verification |
|---|---|---|
-| E2E-MCP-MARKET-NET-BOUNDARY | URL guard rejects credentials, loopback, private, special-use IPv4, v4-mapped, ULA, site-local and link-local bypass forms (trailing dot included); direct/unknown routes pin the checked public address by default, while a fully proxied route uses the session transport and an explicit `allowFakeIp` opt-in can cover transparent-router fake-IP sources without allowing real private answers | deterministic guard assertions; source-contract coverage for DNS pin, proxy route selection, explicit fake-IP scope and bounded responses |
+| E2E-MCP-MARKET-NET-BOUNDARY | The URL guard rejects credentials, cloud metadata, unspecified, multicast and reserved forms (trailing dot included) even when the user typed them, and rejects loopback, private, special-use IPv4, v4-mapped, ULA, site-local and link-local forms for *third-party* hops — a redirect target or a catalog body; the same forms typed by the user into a source field are accepted, with plain `http` behind `networkPolicy.allowInsecureUserEndpoints`; direct/unknown routes pin the checked address by default, while a fully proxied route uses the session transport and an explicit `allowFakeIp` opt-in can cover transparent-router fake-IP sources without allowing real private answers | deterministic guard assertions; source-contract coverage for DNS pin, proxy route selection, explicit fake-IP scope and bounded responses |
| E2E-MCP-MARKET-SEMANTICS | Registry records map to install templates preserving package versions, named/positional runtime/package arguments and required/optional env variables; a remote header variable is recognized in both the registry's `{name}` and the catalog's `${NAME}` spelling, prompts for declared editable values, preserves unbound brace literals, and resolves header-local defaults, fixed values, and optional flags without merging same-named inputs across headers (ADR registry-header-variable-spelling) | deterministic mapping assertions |
| E2E-MCP-MARKET-INSTALL | Builtin catalog entry resolves through `resolveCatalogEntry` and installs via the host `mcp.upsert` RPC; record lands in `~/.agents/servers/` | real host binary, isolated temp HOME |
| E2E-MCP-MARKET-HEADER-SCOPE | Registry header-local `{token}` resolves only in its header; same-named URL path/query tokens remain literal through mapping, resolution, host upsert/list and persistence. URL templates retain only legacy `${NAME}` substitution. When `headerBindings` exists (even empty or partial), unbound tokens in every header stay literal and never consume another header's input or default | shared regressions plus real host binary with isolated temporary storage; remote entry disabled, no network call |
| E2E-MCP-MARKET-partial-header-bindings-stay-literal | Resolve a catalog with only Authorization bound and another header using the same `{token}` / `${token}`; an undeclared `${UNBOUND}` in a third header also remains literal through host upsert/list and disk persistence | real host binary, disabled remote entry, synthetic input and isolated temporary storage; no network call |
-#### E2E-SKILL-MARKET-NET-BOUNDARY: Public-HTTPS skill sources reject private and loopback URLs
+#### E2E-SKILL-MARKET-NET-BOUNDARY: A user-supplied source reaches the LAN, third-party content does not
- **Preconditions**: Shared public-network helpers and the main-process
public-HTTPS client with injectable fetch/DNS/route.
- **Steps**: 1) Classify trailing-dot localhost, IPv4 loopback, IPv4-mapped
- IPv6, ULA, link-local, RFC1918, and `http://` URLs. 2) Resolve a public
- hostname to a private A record. 3) Follow a 302 whose Location is
- `https://127.0.0.1/`. 4) Report a proxied route and a TUN fake-IP answer
+ IPv6, ULA, link-local, RFC1918, and `http://` URLs twice: once as a source URL
+ the user typed, once as a document URL that arrived inside a catalog. 2)
+ Resolve a public hostname to a private A record. 3) Follow a 302 whose Location
+ is `https://127.0.0.1/`. 4) Report a proxied route and a TUN fake-IP answer
(`198.18.0.1`), the same answer on a `DIRECT` route, on an unreadable route,
and on a route list that offers `DIRECT`. 5) Let a first hop be proxied and
its redirect target direct.
-- **Expected**: Every bypass form is rejected. A public CDN URL is accepted.
- DNS that yields a private address and a redirect onto loopback both throw a
- policy error without fetching the private target. A judged refusal is not
+- **Expected**: A source URL the user typed may be a loopback or LAN catalog —
+ `https` always, `http` only under
+ `networkPolicy.allowInsecureUserEndpoints` — while the same address as a
+ *document* URL inside a catalog, or as a redirect target, is rejected; cloud
+ metadata, `unspecified`, multicast and reserved addresses are rejected on every
+ input. A public CDN URL is accepted. A source that resolves to a private
+ address is fetched rather than refused, and a third-party hop that resolves to
+ one throws a policy error without fetching the private target.
retried; a local resolver that answered nothing is, and is reported as
`NETWORK_RESOLVE_FAILED` (`kind` `unresolved`) rather than as an address-check
refusal — the guard reached no verdict, so nothing may claim it did. An address
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 72cdb22e8..25348c841 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -1299,6 +1299,7 @@ D193, and D194.
| D188 | Replace Chat profile with Plan state | *(superseded by D189)* **PI-Desktop has one pi Agent and one product selector: `Agent | Plan`. Plan is that Agent after entering planning state, never a second Agent, planner model, planner service, or permission mode. Agent remains the default. Persisted sessions, app defaults, and scheduled values stored as `chat` migrate to `plan`; the internal `page = "chat"` route may remain as a conversation-surface detail. Plan exposes `Read`, `Glob`, `Grep`, `BrowserPreview`, `Bash`, `CompactContext`, and `ExitPlanMode`; it denies `Write`, `Edit`, plugin tools, and unknown tools. Plan retains permission-mode selection: Bash prompts under `ask` and `accept-edits`, and runs without confirmation under `auto`, so Plan is planning intent rather than a strict read-only security profile.** | Historical pre-checkpoint Plan contract; retained to explain the supersession chain |
| D189 | Plan checkpoint artifact, approval, and execution epoch | **The same pi Agent uses `Agent | Plan`, with Agent default. Plan calls `SubmitPlan(title, markdown, question)` as the only tool in its assistant batch. Rust host-core writes the submitted Markdown bytes unchanged to a new immutable unique file under `<workspaceRoot>/.pi/plan/*.md`; it stores the relative artifact path, SHA-256, and byte size together with structured title/question fields in the existing `plan_approvals` row. No title/question wrapper is added and no prior artifact is replaced. The approval surface displays title, question, an artifact opener, absolute expiry, and status, and offers only Approve or Reject. Approve requires an explicit `ask`, `accept-edits`, or `auto` permission mode, with Ask selected by default; Reject carries no mode. The approval expires at one absolute 30-minute deadline and uses `PLAN_APPROVAL_TIMEOUT`. The same `plan_approvals` row carries `execution_id` and `execution_state` through `queued → running → completed|interrupted`. A startup transaction marks prior pending approvals and queued/running execution states interrupted before serving RPC; no work is replayed. Pending interruption/rejection/expiry leaves the session Plan; an already-approved queued/running interruption leaves the session Agent. One active turn, idle-only configuration, and one pending approval/queued-or-running execution per session are enforced. Scheduled Plan is rejected before provider, artifact, or queue work with `PLAN_REQUIRES_INTERACTIVE_SESSION`. Protocol v9 and storage schema v10 carry the contract without a serialized process-epoch field.** | Immutable host artifacts preserve the submitted checkpoint while one approval/execution row and a startup process fence prevent restart replay without losing the already-approved Agent state |
| D190 | Selectable command shell catalog and execution identity | **Host-core exposes stable platform-aware catalog IDs: `windows-powershell`, `cmd`, `git-bash`, and `bash`; the platform catalog contains only IDs supported by that platform. `defaultCommandShell` persists in host settings, and settings writes reject unavailable or wrong-platform IDs. If a persisted choice later becomes unavailable, the effective shell intentionally falls back to the first available platform shell. The `Bash` tool and `tools.execute` protocol name remain unchanged; each turn pins the effective shell ID and dialect, and host rejects a stale ID/dialect before spawn with `COMMAND_SHELL_CHANGED`. Shell identity is the catalog selection, not an executable path hash. Bash streams stdout and stderr separately, uses a mandatory 60-second default timeout with a 1–300 second override, and cancellation/timeout shuts down the complete process tree.** | Users can choose the command language without multiplying protocol tools, while platform validation, explicit fallback, and turn-pinned catalog identity keep execution predictable |
+| D604 | Trust the network endpoints the user enters themselves | **Amend ADR 0243 / 0245 / 0247 for user-supplied URLs; follow ADR 0142 / 0257 / 0300. A URL the person typed into a settings field — a market source, a git remote, an MCP OAuth endpoint, a generated-image URL — is judged by the user-endpoint policy: loopback, RFC1918, CGNAT, link-local, ULA, site-local and `.local` are reachable, and plain `http` needs the host-owned `networkPolicy.allowInsecureUserEndpoints` opt-in (default off). Third-party content keeps the public-only rule with the checked address pinned: a registry record, a catalog body, a document URL inside a catalog, and every redirect target. Cloud metadata, `unspecified`, multicast, reserved and documentation addresses stay refused on every input. The default proxy bypass list gains `10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16`. No host protocol or storage schema bump: `networkPolicy.allowInsecureUserEndpoints` is one boolean in the existing app settings, validated on write.** | Refusing a LAN address the user typed did not remove the request — it moved the same work into a shell or a browser next to the app, so the boundary cost the feature without preventing a decision the user had already made. Third-party content is where the SSRF risk lives, so that half of the boundary is unchanged. See ADR 0304. |
## 2026-08-05 — Agent-only mode
@@ -4222,6 +4223,28 @@ D193, and D194.
data directory. Portable requests user execution level.
- See ADR 0197 and E2E-211.
+## 2026-09-22 — Trust the network endpoints the user enters themselves (D604)
+
+- An endpoint the user typed themselves — a model base URL, an MCP server, a
+ market source, a git remote, a generated-image URL — may resolve to loopback,
+ RFC1918, CGNAT, link-local, ULA, site-local or `.local`. Plain `http` to such
+ an endpoint needs the host-owned
+ `settings.networkPolicy.allowInsecureUserEndpoints` opt-in (default off);
+ `https` to a LAN host needs no opt-in.
+- Third-party content is unchanged. A registry record, a market catalog body, a
+ document URL inside a catalog and every HTTP redirect target keep the
+ public-only policy with the checked address pinned to the connection. The
+ shared client takes the origin of each hop, and only the first hop of a request
+ the user started may be `user`.
+- Cloud metadata (`169.254.169.254`, `100.100.100.200`, `fd00:ec2::254`,
+ `metadata.google.internal`, `metadata`, `instance-data`), `unspecified`,
+ multicast, reserved and documentation addresses stay refused everywhere,
+ including in a user-supplied field.
+- The default proxy bypass list gains the private ranges, so a configured proxy
+ no longer swallows a local model server, NAS or MCP endpoint. See
+ `05-security/01-security.md` §4.1/§4.2, `04-ux/06-settings-ia.md`, and
+ ADR 0304.
+
## 2026-09-22 — Windows portable delivery uses a normal ZIP (D603)
- Decision D603 amends D364 / ADR 0022 / ADR 0197. The Windows x64 lane now
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 0db2dba8c..1471e292e 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -68,7 +68,7 @@ type AppError = {
| `APPROVAL_STALE` | 不 | RACP:审批已被处理或属于更早的回合 |
| `PAYLOAD_TOO_LARGE` | 不 | RACP:帧超过协商的大小上限 |
| `TIMEOUT` | 是的 | 通用超时 |
-| `NETWORK_POLICY_BLOCKED` | 不 | 主进程公网策略守卫拒绝了一次抓取,因为它**判定了**目标:URL 未通过公网 HTTPS 语法检查,或本地 DNS 解析返回了策略判定为非公网的地址——其中包括本地代理生成的 fake-IP 占位地址(ADR 0243)。仅桌面端使用;拒绝即判定,因此在地址改变前重试不会成功。本地解析完全没有返回答案时改用 `NETWORK_RESOLVE_FAILED`(issue #419)。 |
+| `NETWORK_POLICY_BLOCKED` | 不 | 主进程公网策略守卫拒绝了一次抓取,因为它**判定了**目标:URL 未通过公网 HTTPS 语法检查,或本地 DNS 解析返回了策略判定为非公网的地址——其中包括本地代理生成的 fake-IP 占位地址(ADR 0243)。仅桌面端使用;拒绝即判定,因此在地址改变前重试不会成功。本地解析完全没有返回答案时改用 `NETWORK_RESOLVE_FAILED`(issue #419)。自 ADR 0304 起,用户自己填写的端点可以解析到本机回环或局域网地址,因此该错误码现在只针对两类首跳:命中完全无服务语义的地址类别(云元数据、unspecified、multicast、reserved),或第三方跳——重定向目标、目录正文、registry 记录。 |
| `NETWORK_RESOLVE_FAILED` | 是的 | 主进程公网策略守卫无法判定目标主机:本地 DNS 解析没有返回答案,或在返回前抛错。请求仍与策略拒绝一样被拒,但没有判定任何地址,因此任何界面或日志都不得把它描述成地址校验的判定结果。与 `NETWORK_ERROR` 不同,后者是请求本身的失败。可重试:当解析器或代理开始应答同一主机时,同一请求即可成功(ADR 0243,issue #419)。 |
| `HOST_SHUTTING_DOWN` | 是的 | 主机收到 EOF 正在排空;调用被拒绝而不是被启动 |
| `RATE_LIMITED` | 是的 | 某个按调用方计的主机预算(插件会话导入、批量操作)在其窗口内被超出 |
diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index 302192489..67f9db85c 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -76,7 +76,8 @@
共享的本机选择契约适用于每个应用程序表面
- **网络**卡:
- **代理**:分段控件 — 系统 / 直连 / 自定义。默认是系统(Chromium 跟随操作系统代理)。直连禁用代理。自定义将一个 HTTP、HTTPS 或 SOCKS5 URL 应用到应用自有出站请求(模型调用、扩展市场、更新、模型目录、插件 `net.fetch`、内置浏览器)。工作区 Bash 和 OAuth 用的系统浏览器不会被改写。
- - 自定义显示代理 URL(含 `user:pass@`)、默认 `localhost,127.0.0.1,::1,<local>` 的绕过列表,以及一次走该代理的测试。带认证的 URL 通过回环 SOCKS5 中继交给 Chromium(issue #490)。选择持久化为可选 `AppSettings.networkProxy`。无协议/存储版本升级(D340 / ADR 0177)。
+ - 自定义显示代理 URL(含 `user:pass@`)、默认 `localhost,127.0.0.1,::1,<local>,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16` 的绕过列表(本机、本地模型与所有局域网服务直连,不被代理吞掉),以及一次走该代理的测试。带认证的 URL 通过回环 SOCKS5 中继交给 Chromium(issue #490)。选择持久化为可选 `AppSettings.networkProxy`。无协议/存储版本升级(D340 / ADR 0177)。
+ - **自填端点的明文 HTTP**:一个复选框,持久化为 `AppSettings.networkPolicy.allowInsecureUserEndpoints`(默认关闭)。开启后,你自己填写的端点(模型服务、MCP 服务器、市场源)可以用 `http` 访问;风险提示说明该连接不加密、同一网段的人可以读到该端点接受的一切凭据。https 访问局域网主机不需要该开关(ADR 0304)。
- 平台支持的**关闭行为**仍保留在常规中,因为它改变的是
应用程序窗口行为,而不是智能体行为。
- 文件打开目标、菜单栏行为和底部面板行为不是
diff --git a/docs/zh-CN/spec/05-security/01-security.md b/docs/zh-CN/spec/05-security/01-security.md
index a0302c408..82378819d 100644
--- a/docs/zh-CN/spec/05-security/01-security.md
+++ b/docs/zh-CN/spec/05-security/01-security.md
@@ -98,10 +98,14 @@ CDP 插件工具在 Plan 中仍被拒绝)。 Bash 在 Plan 中仍然可用:
渲染层不拉取技能目录或 SKILL.md。Electron 主进程按公网策略发起 HTTPS 请求(ADR 0243 / D413,由 ADR 0272 / D436 修订):仅 `https`、共享的公网主机语法检查、`redirect: "manual"`,以及按请求实际会走的线路逐跳判定。每一跳之前,客户端都会向承载 `net.fetch` 的会话询问它自己的代理判定(`Session.resolveProxy`):`proxied` 线路上按线路判定,因此容忍解析器自身产物的那一类(`benchmark`,TUN fake-IP);`direct` 或读不出线路时默认保留完整的本地分类,回环、RFC1918、ULA、link-local、mapped IPv6 以及其他所有非公网类别一律拒绝。显式 `allowFakeIp` 选项仅可为透明路由器/TUN 部署额外放行 benchmark 占位地址。安装只通过 `skills.create` 写入 markdown。内联相邻 markdown 后仍受 128 KiB 宿主上限约束。
+用户自己填写的源地址改由 ADR 0304 判定:可以是回环或局域网目录服务,明文 `http` 需要先在设置里开启 `networkPolicy.allowInsecureUserEndpoints`。来自目录正文内部的文档 URL、以及每一次重定向目标,仍然沿用上面的公网策略。
+
MCP 市场只接受无凭据的公网 HTTPS 源和目录端点。Main 在每一跳前向承载请求的同一 Electron session 询问代理线路。在完整的 `proxied` 线路上使用 Chromium `net.fetch`,让系统/PAC 和自定义代理能够解析 fake-IP 主机;此时容忍本地解析器的 `benchmark` fake-IP 类别,但真实私网及其他非公网类别仍然拒绝。在 `direct` 或 `unknown` 线路上保留原有 Node HTTPS 路径,把选中的公网地址固定到 socket,同时保留原主机名用于 TLS SNI 和 HTTP Host;显式 `allowFakeIp` 选项仅额外允许 benchmark 答案,绝不允许其他非公网类别。重定向手动跟随、仅限 HTTPS、最多五跳,并在每次连接前重新检查。响应上限为 4 MiB,请求共享 8 秒截止时间,源、缓存和条目数量均有界。跨 origin 的用户 MCP 重定向不会转发调用方 header。
手动配置的用户 MCP 仍遵循 ADR 0142,可以显式使用本地/LAN 端点;市场路径不会扩大该策略。
+用户自己填写的市场源地址同样由 ADR 0304 判定:可以是回环或局域网端点,明文 `http` 需要开启 `networkPolicy.allowInsecureUserEndpoints`。源返回的任何内容——registry 记录、目录正文、重定向目标——仍然沿用上面的公网策略。
+
## 5. 命令执行
- Bash默认需要确认(风险分级权限卡);在
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index a52de6b78..1d4f6ee4e 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -7700,12 +7700,12 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture
- **里程碑**:M2
- **状态**:单元覆盖(`packages/shared/src/composer-trigger.test.ts`、`apps/desktop/test/composer-ime.test.mjs`);渲染桌面旅程为草稿(除非明确要求,不本地运行 E2E)
-#### E2E-CLONE-public-hostname-rejects-private
+#### E2E-CLONE-accepts-a-lan-remote-and-rejects-metadata
- **前提条件**:首页项目切换菜单的「克隆 Git 项目」可用。
-- **步骤**:1)输入 `https://127.0.0.1/org/repo.git`、`http://localhost/org/repo.git`、`https://10.0.0.5/org/repo.git` 和 `[email protected]:org/repo.git`。2)输入 `https://github.com/org/repo.git` 和 `[email protected]:org/repo.git`。
-- **预期**:私网、回环和链路本地远程在 `git clone` 运行前被拒绝。公网 GitHub HTTPS 与 SSH 仍解析出文件夹名。`file:` 和带密码的 URL 继续被拒绝。
-- **链接规格**:`04-ux/01-ui-ia.md`、ADR 0247、D416
+- **步骤**:1)输入 `https://192.168.1.5/org/repo.git`、`http://10.0.0.7/org/repo.git` 和 `[email protected]:org/repo.git`。2)输入 `https://169.254.169.254/org/repo.git` 和 `https://metadata.google.internal/org/repo.git`。3)输入 `https://github.com/org/repo.git` 和 `[email protected]:org/repo.git`。
+- **预期**:用户自己填写的局域网或回环远端被接受并解析出文件夹名,因为这是用户自己的地址。云元数据主机仍然拒绝,`file:` 与带密码的 URL 也一样,都在 `git clone` 运行前拒绝。公网 GitHub HTTPS 与 SSH 仍解析成功。
+- **链接规格**:`04-ux/01-ui-ia.md`、ADR 0247、ADR 0304、D416
- **验收**:安全、D(工作区)
- **里程碑**:M5
- **状态**:单元覆盖(`apps/desktop/test/git-clone.test.mjs`)
@@ -7970,18 +7970,18 @@ runner 会在运行时的隔离临时目录中生成六个插件形态 fixture
| ID | 场景 | 验证 |
|---|---|---|
-| E2E-MCP-MARKET-NET-BOUNDARY | URL guard 拒绝凭据、回环、私网、special-use IPv4、v4-mapped、ULA、site-local 和 link-local 及尾点绕过形态;direct/unknown 默认固定已检查的公网地址,完整 proxied 线路使用 session 传输,显式 `allowFakeIp` 可覆盖透明路由器 fake-IP 源但不允许真实私网答案 | 确定性 guard 断言;DNS pin、代理线路选择、fake-IP 选项范围与响应上限 source-contract 覆盖 |
+| E2E-MCP-MARKET-NET-BOUNDARY | URL guard 拒绝凭据、云元数据、unspecified、multicast、reserved 及尾点绕过形态——即使由用户自己填写;对**第三方跳**(重定向目标、目录正文)拒绝回环、私网、special-use IPv4、v4-mapped、ULA、site-local 与 link-local;同一形态由用户填进源地址字段时被接受,明文 `http` 需 `networkPolicy.allowInsecureUserEndpoints`;direct/unknown 默认固定已检查的地址,完整 proxied 线路使用 session 传输,显式 `allowFakeIp` 可覆盖透明路由器 fake-IP 源但不允许真实私网答案 | 确定性 guard 断言;DNS pin、代理线路选择、fake-IP 选项范围与响应上限 source-contract 覆盖 |
| E2E-MCP-MARKET-SEMANTICS | Registry 记录映射为安装模板时保留包版本、named/positional runtime/package 参数与 required/optional 环境变量语义;远端 header 变量同时识别注册表的 `{name}` 与目录的 `${NAME}` 两种写法,仅为已声明的可编辑值显示输入,保留未声明花括号字面量,并按各 header 的作用域处理默认值、固定值与可选标记,不合并不同 header 的同名输入(ADR registry-header-variable-spelling) | 确定性映射断言 |
| E2E-MCP-MARKET-INSTALL | 内置目录条目经 `resolveCatalogEntry` 解析并通过宿主 `mcp.upsert` RPC 安装;记录落盘 `~/.agents/servers/` | 真实宿主二进制,隔离临时 HOME |
| E2E-MCP-MARKET-HEADER-SCOPE | Registry header-local `{token}` resolves only in its header; same-named URL path/query tokens remain literal through mapping, resolution, host upsert/list and persistence. URL templates retain only legacy `${NAME}` substitution. When `headerBindings` exists (even empty or partial), unbound tokens in every header stay literal and never consume another header's input or default | shared regressions plus real host binary with isolated temporary storage; remote entry disabled, no network call |
| E2E-MCP-MARKET-partial-header-bindings-stay-literal | Resolve a catalog with only Authorization bound and another header using the same `{token}` / `${token}`; an undeclared `${UNBOUND}` in a third header also remains literal through host upsert/list and disk persistence | real host binary, disabled remote entry, synthetic input and isolated temporary storage; no network call |
-#### E2E-SKILL-MARKET-NET-BOUNDARY:技能源公网 HTTPS 策略拒绝私网与回环
+#### E2E-SKILL-MARKET-NET-BOUNDARY:用户自填源可达局域网,第三方内容不行
- **前提条件**:共享 public-network helper,以及可注入 fetch/DNS/线路 的主进程公网 HTTPS 客户端。
-- **步骤**:1)分类 trailing-dot localhost、IPv4 回环、IPv4-mapped IPv6、ULA、link-local、RFC1918 与 `http://`。2)将公网主机名解析到私网 A 记录。3)跟随 Location 为 `https://127.0.0.1/` 的 302。4)报告 `proxied` 线路与 TUN fake-IP 答案(`198.18.0.1`),同一答案在 `DIRECT` 线路、读不出线路、以及列表中含 `DIRECT` 的线路上的表现。5)让第一跳为 `proxied`,其重定向目标为 `direct`。
-- **预期**:上述绕过形态全部拒绝;公共 CDN 放行。解析到私网地址或 redirect 到回环会抛出策略错误,且不会请求私网目标。判定型拒绝不重试;本地解析没有返回答案时会重试,并且报为 `NETWORK_RESOLVE_FAILED`(`kind` 为 `unresolved`),而不是报成地址校验拒绝——守卫并未得出判定,任何文案都不得声称它得出了。本地代理伪造的 fake-IP 答案(如 Clash 默认的 `198.18.0.0/15`)在守卫判定它的线路上——`direct` 或读不出线路——仍被拒绝且不重试,并以 `kind` 为 `fake-ip`、`reason` 为 `non-public-address`、`addressKind` 为 `benchmark` 记录,与真实私网目标(`kind` 为 `policy`、`addressKind` 为 `private`)清楚区分——对后者守卫判定了目标,对前者没有;同一答案在 `proxied` 线路上放行。其余每次拒绝都带上 `NETWORK_POLICY_BLOCKED`(spec 08 §3.1)及其 `reason`、被解析到的地址、地址类别与判定该地址的线路,使安装面板能给出原因并提供重试,而不是让安装按钮无解释地保持禁用;市场列表也能把被拒绝的源与单纯不可达的源区分开。其他所有非公网类别在任何线路上都拒绝;每一个重定向跳都按自己的线路判定(ADR 0272)。
+- **步骤**:1)把 trailing-dot localhost、IPv4 回环、IPv4-mapped IPv6、ULA、link-local、RFC1918 与 `http://` 各分类两次:一次作为用户自己填写的源地址,一次作为目录正文里的文档 URL。2)将公网主机名解析到私网 A 记录。3)跟随 Location 为 `https://127.0.0.1/` 的 302。4)报告 `proxied` 线路与 TUN fake-IP 答案(`198.18.0.1`),同一答案在 `DIRECT` 线路、读不出线路、以及列表中含 `DIRECT` 的线路上的表现。5)让第一跳为 `proxied`,其重定向目标为 `direct`。
+- **预期**:用户自己填写的源地址可以是回环或局域网目录——`https` 始终允许,`http` 仅在 `networkPolicy.allowInsecureUserEndpoints` 打开时允许;而同一地址作为目录内部的文档 URL 或重定向目标时一律拒绝;云元数据、`unspecified`、`multicast`、`reserved` 在任何输入上都拒绝。公共 CDN 放行。用户源解析到私网地址会被正常抓取;第三方跳解析到私网地址会抛出策略错误,且不会请求私网目标。判定型拒绝不重试;本地解析没有返回答案时会重试,并且报为 `NETWORK_RESOLVE_FAILED`(`kind` 为 `unresolved`),而不是报成地址校验拒绝——守卫并未得出判定,任何文案都不得声称它得出了。本地代理伪造的 fake-IP 答案(如 Clash 默认的 `198.18.0.0/15`)在守卫判定它的线路上——`direct` 或读不出线路——仍被拒绝且不重试,并以 `kind` 为 `fake-ip`、`reason` 为 `non-public-address`、`addressKind` 为 `benchmark` 记录,与真实私网目标(`kind` 为 `policy`、`addressKind` 为 `private`)清楚区分——对后者守卫判定了目标,对前者没有;同一答案在 `proxied` 线路上放行。其余每次拒绝都带上 `NETWORK_POLICY_BLOCKED`(spec 08 §3.1)及其 `reason`、被解析到的地址、地址类别与判定该地址的线路,使安装面板能给出原因并提供重试,而不是让安装按钮无解释地保持禁用;市场列表也能把被拒绝的源与单纯不可达的源区分开。其他所有非公网类别在任何线路上都拒绝;每一个重定向跳都按自己的线路判定(ADR 0272)。
- **链接规格**:`05-security/01-security.md`、ADR 0243、ADR 0272、`03-runtime/01-ipc-protocol.md` §12b
- **验收**:Security、Quality
- **里程碑**:M6+
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index b0eb74014..48602a450 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -1173,6 +1173,7 @@ D193 和 D194。
| D188 | 将聊天配置文件替换为 Plan 状态 | *(被 D189 取代)* **PI-Desktop 有 1 个 pi Agent 和 1 个产品选择器:`Agent | 计划`. Plan is that Agent after entering planning state, never a second Agent, planner model, planner service, or permission mode. Agent remains the default. Persisted sessions, app defaults, and scheduled values stored as `聊天` migrate to `计划`; the internal `页面 = “聊天”` route may remain as a conversation-surface detail. Plan exposes `读取`, `Glob`, `Grep`, `浏览器预览`, `Bash`, `CompactCon text`, and `ExitPlanMode`; it denies `Write`, `编辑`, plugin tools, and unknown tools. Plan retains permission-mode selection: Bash prompts under `ask` and `accept-edits`, and runs without confirmation under `auto`,因此 Plan 是计划意图而不是严格的只读安全配置文件。** | 历史预检查点Plan合约;保留解释取代链 |
| D189 | Plan 检查点工件、批准和执行纪元 | **相同的 pi Agent 使用 `Agent | Plan`, with Agent default. Plan calls `SubmitPlan(标题, markdown, 问题)` as the only tool in its assistant batch. Rust host-core writes the submitted Markdown bytes unchanged to a new immutable unique file under `<workspaceRoot>/.pi/plan/*.md`; it stores the relative artifact path, SHA-256, and byte size together with structured title/question fields in the existing `plan_approvals` row. No title/question wrapper is added and no prior artifact is replaced. The approval surface displays title, question, an artifact opener, absolute expiry, and status, and offers only Approve or Reject. Approve requires an explicit `ask`, `accept-edits`, or `auto` permission mode, with Ask selected by default; Reject carries no mode. The approval expires at one absolute 30-minute deadline and uses `PLAN_APPROVAL_TIMEOUT`. The same `plan_approvals` row carries `execution_id` and `execution_state` through `queued → 运行 → 已完成 | 中断了`. A startup transaction marks prior pending approvals and queued/running execution states interrupted before serving RPC; no work is replayed. Pending interruption/rejection/expiry leaves the session Plan; an already-approved queued/running interruption leaves the session Agent. One active turn, idle-only configuration, and one pending approval/queued-or-running execution per session are enforced. Scheduled Plan is rejected before provider, artifact, or queue work with `PLAN_REQUIRES_INTERACTIVE_SESSION`。协议 v9 和存储模式 v10 携带的合约没有序列化的 process-epoch 字段。** | 不可变的主机工件保留提交的检查点,同时一个 approval/execution 行和启动进程栅栏可防止重新启动重播,而不会丢失已批准的 Agent 状态 |
| D190 | 可选择的命令 shell 目录和执行标识 | **主机核心公开稳定的平台感知目录 ID:`windows-powershell`、`cmd`、`git-bash` 和 `bash`;平台目录仅包含该平台支持的 ID。 `defaultCommandShell` 保留在主机设置中,并且设置写入拒绝不可用或错误的平台 ID。如果持久选择稍后变得不可用,则有效 shell 会有意回退到第一个可用的平台 shell。 `Bash` 工具和 `tools.execute` 协议名称保持不变;每个回合都会固定有效的 shell ID 和方言,并且主机在使用 `COMMAND_SHELL_CHANGED` 生成之前拒绝过时的 ID/dialect。 Shell 标识是目录选择,而不是可执行路径哈希。 Bash 分别流式传输 stdout 和 stderr,使用强制的 60 秒默认超时和 1-300 秒覆盖,并且 cancellation/timeout 关闭完整的进程树。** | 用户可以选择命令语言,而无需增加协议工具,而平台验证、显式回退和转固定目录身份可保持执行的可预测性 |
+| D604 | 信任用户自己填写的网络端点 | **对用户填写的 URL 修订 ADR 0243 / 0245 / 0247;沿用 ADR 0142 / 0257 / 0300。用户自己在设置里填写的 URL——市场源、git 远端、MCP OAuth 端点、生成图片 URL——改按"用户端点"策略判定:回环、RFC1918、CGNAT、link-local、ULA、site-local 与 `.local` 都可达,明文 `http` 需要主机侧 `networkPolicy.allowInsecureUserEndpoints` 开关(默认关闭)。第三方内容仍只允许公网并把校验过的地址固定到连接:registry 记录、目录正文、目录内部的文档 URL、以及每一次重定向目标。云元数据、`unspecified`、multicast、reserved、documentation 在任何输入上一律拒绝。默认代理绕过列表增加 `10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16`。不改主机协议、不改存储 schema:`networkPolicy.allowInsecureUserEndpoints` 只是既有 app settings 里的一个布尔字段,写入时校验。** | 拒绝用户自己填写的局域网地址并没有消除那次请求——它只是把同样的工作搬到应用旁边的 shell 或浏览器里,因此这条边界牺牲了功能,却没有阻止用户已经做出的决定。SSRF 风险在第三方内容那一侧,所以边界的那一半保持不变。见 ADR 0304。 |
## 2026-08-05 — 仅代理模式
@@ -3547,6 +3548,25 @@ D193 和 D194。
user 执行级别。
- 参见 ADR 0197 与 E2E-211。
+## 2026-09-22 —— 信任用户自己填写的网络端点(D604)
+
+- 用户自己填写的端点——模型 base URL、MCP 服务器、市场源、git 远端、
+ 生成图片 URL——可以解析到回环、RFC1918、CGNAT、link-local、ULA、
+ site-local 或 `.local`。明文 `http` 需要主机侧
+ `settings.networkPolicy.allowInsecureUserEndpoints` 开关(默认关闭);
+ `https` 访问局域网主机不需要开关。
+- 第三方内容不变。registry 记录、市场目录正文、目录内部的文档 URL、
+ 以及每一次 HTTP 重定向目标,仍然只允许公网,并把校验过的地址固定到
+ 连接上。共享客户端按每一跳的来源判定,只有用户发起请求的首跳可以是
+ `user`。
+- 云元数据(`169.254.169.254`、`100.100.100.200`、`fd00:ec2::254`、
+ `metadata.google.internal`、`metadata`、`instance-data`)、`unspecified`、
+ multicast、reserved、documentation 地址在任何输入上一律拒绝,包括用户
+ 自己填写的字段。
+- 默认代理绕过列表增加私网段,配置了代理之后不再吞掉本机模型服务、NAS
+ 或 MCP 端点。见 `05-security/01-security.md` §4.1/§4.2、
+ `04-ux/06-settings-ia.md` 与 ADR 0304。
+
## 2026-09-22 —— Windows 便携交付改为普通 ZIP(D603)
- 决策 D603 修订 D364 / ADR 0022 / ADR 0197。Windows x64 通道现在在 NSIS 安装程序
diff --git a/packages/agent-runtime/src/image-generation/download.ts b/packages/agent-runtime/src/image-generation/download.ts
index 523fce36e..513e628e0 100644
--- a/packages/agent-runtime/src/image-generation/download.ts
+++ b/packages/agent-runtime/src/image-generation/download.ts
@@ -1,5 +1,9 @@
import { lookup } from "node:dns/promises";
-import { isIP } from "node:net";
+import {
+ classifyIpLiteral,
+ isAcceptableUserEndpointAddress,
+ isCloudMetadataAddress,
+} from "@pi-desktop/shared";
import { Agent, fetch as fetchPinned } from "undici";
export const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
@@ -34,33 +38,37 @@ export async function boundedBytes(
}
}
-/** Deny non-public destinations, including mapped IPv6 and cloud metadata. */
+/**
+ * Whether a resolved address may be dialed for a generated image.
+ *
+ * The URL comes from the image provider's own response, but the provider is an
+ * endpoint the user configured, and a self-hosted one (ComfyUI, SD-WebUI) hands
+ * back its own LAN address. Judging it by the third-party rule made those setups
+ * unusable, so loopback, RFC1918, CGNAT, link-local, ULA and site-local are all
+ * reachable here, and the address classes are taken from `@pi-desktop/shared`
+ * rather than re-derived so they cannot drift. Cloud metadata stays refused on
+ * every input, as do the classes that name no destination at all (unspecified,
+ * multicast, reserved, documentation, benchmark — a fake-IP answer is a proxy
+ * placeholder, not a host this process dials).
+ */
export function publicImageAddress(address: string): boolean {
- if (isIP(address) === 4) {
- const [a, b, c] = address.split(".").map(Number);
- return !(
- a === 0 ||
- a === 10 ||
- a === 127 ||
- a >= 224 ||
- (a === 100 && b >= 64 && b <= 127) ||
- (a === 169 && b === 254) ||
- (a === 172 && b >= 16 && b <= 31) ||
- (a === 192 && (b === 168 || b === 0 || (b === 88 && c === 99))) ||
- (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) ||
- (a === 203 && b === 0 && c === 113)
- );
- }
- if (isIP(address) === 6) {
- const lower = address.toLowerCase();
- return (
- /^[23][0-9a-f]{3}:/.test(lower) && !lower.startsWith("2001:") && !lower.startsWith("2002:")
- );
- }
- return false;
+ if (typeof address !== "string" || !address) return false;
+ if (isCloudMetadataAddress(address)) return false;
+ return isAcceptableUserEndpointAddress(address, classifyIpLiteral(address), "direct");
}
-/** Pin the checked DNS answer to the connection; never forward provider headers. */
+/**
+ * Pin the checked DNS answer to the connection; never forward provider headers.
+ *
+ * Plain `http` and any port are accepted because the realistic target is a
+ * self-hosted generator on the user's own machine or LAN, where TLS and port
+ * 443 are the exception. `@pi-desktop/agent-runtime` has no access to the app's
+ * `networkPolicy.allowInsecureUserEndpoints` setting (it must not import
+ * Electron main-process modules), so plaintext to a private address cannot be
+ * gated on the user's opt-in here; the trade-off is accepted because the
+ * endpoint this dials is the one the user configured, and the response is
+ * still size-capped and stripped of provider-supplied headers.
+ */
export async function downloadGeneratedImage(
raw: string,
signal: AbortSignal,
@@ -72,10 +80,9 @@ export async function downloadGeneratedImage(
throw imageError("IMAGE_INVALID_URL");
}
if (
- url.protocol !== "https:" ||
+ (url.protocol !== "https:" && url.protocol !== "http:") ||
url.username ||
- url.password ||
- (url.port && url.port !== "443")
+ url.password
) {
throw imageError("IMAGE_INVALID_URL");
}
diff --git a/packages/agent-runtime/src/image-generation/image-generation.test.ts b/packages/agent-runtime/src/image-generation/image-generation.test.ts
index 127c5865d..70963684b 100644
--- a/packages/agent-runtime/src/image-generation/image-generation.test.ts
+++ b/packages/agent-runtime/src/image-generation/image-generation.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from "vitest";
import { generateImageBatch, generateOneImage, imageGenerationUrl } from "./index.js";
-import { publicImageAddress, generatedImageType, boundedBytes } from "./download.js";
+import {
+ publicImageAddress,
+ generatedImageType,
+ boundedBytes,
+ downloadGeneratedImage,
+} from "./download.js";
import { imageGenerationPrompts, parseImageGenerationBinding } from "@pi-desktop/shared";
const png =
@@ -151,21 +156,59 @@ describe("image generation", () => {
vi.useRealTimers();
}
});
- it("rejects unsafe image addresses, forged images and oversized bodies", async () => {
+ it("allows private and loopback image addresses but refuses metadata and unnamed classes", async () => {
for (const address of [
"127.0.0.1",
"10.0.0.1",
- "169.254.169.254",
"172.16.0.1",
- "192.168.0.1",
+ "192.168.1.5",
+ "100.64.0.1",
+ "169.254.1.1",
"::1",
"::ffff:127.0.0.1",
"fc00::1",
+ "fe80::1",
+ ])
+ expect(publicImageAddress(address)).toBe(true);
+ for (const address of [
+ "169.254.169.254",
+ "100.100.100.200",
+ "fd00:ec2::254",
+ "0.0.0.0",
+ "::",
+ "224.0.0.1",
+ "ff02::1",
+ "240.0.0.1",
+ "192.0.2.1",
"2002:7f00:1::",
+ "2001:db8::1",
+ "",
+ "not-an-ip",
])
expect(publicImageAddress(address)).toBe(false);
expect(publicImageAddress("8.8.8.8")).toBe(true);
expect(() => generatedImageType(Buffer.from("<svg>"))).toThrow("IMAGE_INVALID_CONTENT");
await expect(boundedBytes(new Response("oversized"), 2)).rejects.toThrow("IMAGE_TOO_LARGE");
});
+ it("accepts plaintext http on any port, keeps metadata and credentials refused", async () => {
+ const signal = new AbortController().signal;
+ await expect(downloadGeneratedImage("ftp://127.0.0.1:21/image.png", signal)).rejects.toThrow(
+ "IMAGE_INVALID_URL",
+ );
+ await expect(
+ downloadGeneratedImage("http://user:[email protected]:1/image.png", signal),
+ ).rejects.toThrow("IMAGE_INVALID_URL");
+ await expect(
+ downloadGeneratedImage("http://169.254.169.254/latest/meta-data/", signal),
+ ).rejects.toThrow("IMAGE_UNSAFE_URL");
+
+ // A private http URL on a non-443 port clears URL and address validation;
+ // the port below is closed, so the failure is the connection itself.
+ const error = await downloadGeneratedImage("http://127.0.0.1:1/image.png", signal).then(
+ () => null,
+ (reason: unknown) => reason,
+ );
+ expect(error).toBeInstanceOf(Error);
+ expect((error as { errorCode?: string }).errorCode).toBeUndefined();
+ });
});
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 641481486..4e6c0484f 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -607,7 +607,8 @@ sklm: {
namePlaceholder: "Quellenname",
urlHint: "https://…/catalog.json",
documentTooLarge: "Diese Skill überschreitet nach dem Anhängen der Ressourcen das 128-KB-Dokumentlimit.",
- sourceUnsafe: "Quell-URL muss eine öffentliche https-Adresse sein",
+ sourceUnsafe:
+ "Quell-URL muss eine http- oder https-Adresse sein, keine Cloud-Metadaten-Adresse. Für Klartext-HTTP auf dem eigenen Rechner oder im LAN in den Netzwerkeinstellungen „Klartext-HTTP für eigene lokale und LAN-Endpunkte zulassen“ einschalten.",
pageInfo: "Seite {{page}} von {{pages}} · {{total}} Skills",
pagePrev: "Zurück",
pageNext: "Weiter",
@@ -973,7 +974,8 @@ sklm: {
namePlaceholder: "Quellenname",
urlHint: "https://… (Registry-Endpunkt oder Katalog-JSON)",
officialSource: "Offizielle Registry",
- sourceUnsafe: "Quell-URL muss eine öffentliche https-Adresse sein",
+ sourceUnsafe:
+ "Quell-URL muss eine http- oder https-Adresse sein, keine Cloud-Metadaten-Adresse. Für Klartext-HTTP auf dem eigenen Rechner oder im LAN in den Netzwerkeinstellungen „Klartext-HTTP für eigene lokale und LAN-Endpunkte zulassen“ einschalten.",
pageInfo: "Seite {{page}} von {{pages}} · {{total}} Server",
pagePrev: "Zurück",
pageNext: "Weiter",
@@ -1177,6 +1179,11 @@ sklm: {
"proxyTesting": "Wird getestet…",
"proxyTestOk": "Verbunden",
"proxyTestFail": "Verbindung konnte nicht hergestellt werden: {{message}}",
+ "networkAllowInsecureUserEndpoints": "Klartext-HTTP für eigene lokale und LAN-Endpunkte zulassen",
+ "networkAllowInsecureUserEndpointsDesc":
+ "Gilt für Endpunkte, die du selbst einträgst: einen Modelldienst, MCP-Server oder eine Marktquelle auf diesem Rechner oder im LAN. HTTPS zu einer LAN-Adresse braucht diesen Schalter nicht.",
+ "networkAllowInsecureUserEndpointsWarning":
+ "Klartext-HTTP ist nicht verschlüsselt. Wer im selben Netzsegment sitzt, kann diesen Datenverkehr und die Zugangsdaten, die der Dienst annimmt, mitlesen.",
"defaultsTitle": "Standardwerte",
"defaultModel": "Standardmodell",
"defaultModelNone": "Kein KI-Anbieter bereit",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 551ef68be..62366eeea 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -614,7 +614,8 @@ sklm: {
namePlaceholder: "Source name",
urlHint: "https://…/catalog.json",
documentTooLarge: "This skill is larger than the 128 KB document limit after attaching resources.",
- sourceUnsafe: "Source URL must be a public https address",
+ sourceUnsafe:
+ "Source URL must be an http or https address, and not a cloud metadata address. For plain http on your own machine or LAN, turn on “Allow plain HTTP for my own local and LAN endpoints” in Network settings.",
pageInfo: "Page {{page}} of {{pages}} · {{total}} skills",
pagePrev: "Previous page",
pageNext: "Next page",
@@ -845,7 +846,8 @@ sklm: {
namePlaceholder: "Source name",
urlHint: "https://… (registry endpoint or catalog JSON)",
officialSource: "Official registry",
- sourceUnsafe: "Source URL must be a public https address",
+ sourceUnsafe:
+ "Source URL must be an http or https address, and not a cloud metadata address. For plain http on your own machine or LAN, turn on “Allow plain HTTP for my own local and LAN endpoints” in Network settings.",
pageInfo: "Page {{page}} of {{pages}} · {{total}} servers",
pagePrev: "Previous page",
pageNext: "Next page",
@@ -1192,6 +1194,11 @@ sklm: {
proxyTesting: "Testing…",
proxyTestOk: "Connected",
proxyTestFail: "Couldn't connect: {{message}}",
+ networkAllowInsecureUserEndpoints: "Allow plain HTTP for my own local and LAN endpoints",
+ networkAllowInsecureUserEndpointsDesc:
+ "Applies to endpoints you enter yourself: a model service, MCP server, or market source on this machine or your LAN. HTTPS to a LAN address does not need this switch.",
+ networkAllowInsecureUserEndpointsWarning:
+ "Plain HTTP is not encrypted. Anyone on the same network segment can intercept this traffic and the credentials the endpoint accepts.",
defaultsTitle: "Defaults",
defaultModel: "Default model",
defaultModelNone: "No AI provider ready",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index cba2f5032..2cee1a9c7 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -607,7 +607,8 @@ sklm: {
namePlaceholder: "Nombre de la fuente",
urlHint: "https://…/catalog.json",
documentTooLarge: "Esta skill supera el límite de 128 KB del documento tras adjuntar recursos.",
- sourceUnsafe: "La URL debe ser una dirección https pública",
+ sourceUnsafe:
+ "La URL de origen debe ser http o https, no una dirección de metadatos en la nube. Para usar http sin cifrar en tu equipo o la LAN, activa «Permitir HTTP sin cifrar para mis propios servicios locales y de la LAN» en los ajustes de Red.",
pageInfo: "Página {{page}} de {{pages}} · {{total}} skills",
pagePrev: "Anterior",
pageNext: "Siguiente",
@@ -973,7 +974,8 @@ sklm: {
namePlaceholder: "Nombre de la fuente",
urlHint: "https://… (endpoint de registro o JSON de catálogo)",
officialSource: "Registro oficial",
- sourceUnsafe: "La URL debe ser una dirección https pública",
+ sourceUnsafe:
+ "La URL de origen debe ser http o https, no una dirección de metadatos en la nube. Para usar http sin cifrar en tu equipo o la LAN, activa «Permitir HTTP sin cifrar para mis propios servicios locales y de la LAN» en los ajustes de Red.",
pageInfo: "Página {{page}} de {{pages}} · {{total}} servidores",
pagePrev: "Anterior",
pageNext: "Siguiente",
@@ -1177,6 +1179,11 @@ sklm: {
"proxyTesting": "Probando…",
"proxyTestOk": "Conectado",
"proxyTestFail": "No se pudo conectar: ​​{{message}}",
+ "networkAllowInsecureUserEndpoints": "Permitir HTTP sin cifrar para mis propios servicios locales y de la LAN",
+ "networkAllowInsecureUserEndpointsDesc":
+ "Se aplica a las direcciones que escribes tú: un servicio de modelos, un servidor MCP o una fuente del mercado en este equipo o en tu LAN. HTTPS a una dirección de la LAN no necesita esta opción.",
+ "networkAllowInsecureUserEndpointsWarning":
+ "El HTTP sin cifrar no protege la conexión: cualquiera en el mismo segmento de red puede interceptar el tráfico y las credenciales que acepta el servicio.",
"defaultsTitle": "Valores predeterminados",
"defaultModel": "Modelo predeterminado",
"defaultModelNone": "No hay ningún proveedor de IA listo",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 30536d9dd..23f175a15 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -607,7 +607,8 @@ sklm: {
namePlaceholder: "Nom de la source",
urlHint: "https://…/catalog.json",
documentTooLarge: "Cette skill dépasse la limite de 128 Ko une fois les ressources jointes.",
- sourceUnsafe: "L'URL doit être une adresse https publique",
+ sourceUnsafe:
+ "L'URL source doit être une adresse http ou https, pas une adresse de métadonnées cloud. Pour du HTTP en clair sur votre machine ou votre réseau local, activez « Autoriser le HTTP en clair pour mes propres services locaux et du réseau local » dans les réglages Réseau.",
pageInfo: "Page {{page}} sur {{pages}} · {{total}} skills",
pagePrev: "Précédente",
pageNext: "Suivante",
@@ -973,7 +974,8 @@ sklm: {
namePlaceholder: "Nom de la source",
urlHint: "https://… (endpoint de registre ou JSON de catalogue)",
officialSource: "Registre officiel",
- sourceUnsafe: "L'URL doit être une adresse https publique",
+ sourceUnsafe:
+ "L'URL source doit être une adresse http ou https, pas une adresse de métadonnées cloud. Pour du HTTP en clair sur votre machine ou votre réseau local, activez « Autoriser le HTTP en clair pour mes propres services locaux et du réseau local » dans les réglages Réseau.",
pageInfo: "Page {{page}} sur {{pages}} · {{total}} serveurs",
pagePrev: "Précédente",
pageNext: "Suivante",
@@ -1177,6 +1179,11 @@ sklm: {
"proxyTesting": "Test…",
"proxyTestOk": "Connecté",
"proxyTestFail": "Impossible de se connecter : {{message}}",
+ "networkAllowInsecureUserEndpoints": "Autoriser le HTTP en clair pour mes propres services locaux et du réseau local",
+ "networkAllowInsecureUserEndpointsDesc":
+ "Concerne les adresses que vous saisissez vous-même : un service de modèles, un serveur MCP ou une source du marché sur cette machine ou votre réseau local. HTTPS vers une adresse locale n'a pas besoin de cette option.",
+ "networkAllowInsecureUserEndpointsWarning":
+ "Le HTTP en clair n'est pas chiffré : toute personne sur le même segment réseau peut intercepter le trafic et les identifiants acceptés par ce service.",
"defaultsTitle": "Valeurs par défaut",
"defaultModel": "Modèle par défaut",
"defaultModelNone": "Aucun fournisseur d'IA prêt",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index d498d4fed..41752298c 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -616,7 +616,8 @@ sklm: {
namePlaceholder: "소스 이름",
urlHint: "https://…/catalog.json",
documentTooLarge: "리소스를 첨부한 뒤 문서가 128KB 제한을 초과합니다.",
- sourceUnsafe: "소스 URL은 공개 https 주소여야 합니다",
+ sourceUnsafe:
+ "소스 URL은 http 또는 https 주소여야 하며 클라우드 메타데이터 주소는 안 됩니다. 내 컴퓨터나 LAN에서 평문 http를 쓰려면 네트워크 설정에서 “직접 입력한 로컬·LAN 서비스에 평문 HTTP 허용”을 켜세요.",
pageInfo: "{{page}} / {{pages}} 페이지 · 총 {{total}}개",
pagePrev: "이전 페이지",
pageNext: "다음 페이지",
@@ -983,7 +984,8 @@ sklm: {
namePlaceholder: "소스 이름",
urlHint: "https://… (레지스트리 엔드포인트 또는 카탈로그 JSON)",
officialSource: "공식 레지스트리",
- sourceUnsafe: "소스 URL은 공개 https 주소여야 합니다",
+ sourceUnsafe:
+ "소스 URL은 http 또는 https 주소여야 하며 클라우드 메타데이터 주소는 안 됩니다. 내 컴퓨터나 LAN에서 평문 http를 쓰려면 네트워크 설정에서 “직접 입력한 로컬·LAN 서비스에 평문 HTTP 허용”을 켜세요.",
pageInfo: "{{page}} / {{pages}} 페이지 · 총 {{total}}개",
pagePrev: "이전 페이지",
pageNext: "다음 페이지",
@@ -1190,6 +1192,11 @@ sklm: {
proxyTesting: "테스트 중…",
proxyTestOk: "연결됨",
proxyTestFail: "연결할 수 없습니다: {{message}}",
+ networkAllowInsecureUserEndpoints: "직접 입력한 로컬·LAN 서비스에 평문 HTTP 허용",
+ networkAllowInsecureUserEndpointsDesc:
+ "직접 입력한 주소에만 적용됩니다: 이 컴퓨터나 LAN에 있는 모델 서비스, MCP 서버, 마켓 소스. LAN 주소에 HTTPS를 쓰면 이 항목이 필요하지 않습니다.",
+ networkAllowInsecureUserEndpointsWarning:
+ "평문 HTTP는 암호화되지 않습니다: 같은 네트워크 대역에 있는 사람이 이 연결과 서비스가 받는 자격 증명을 가로챌 수 있습니다.",
defaultsTitle: "기본값",
defaultModel: "기본 모델",
defaultModelNone: "사용 가능한 AI 프로바이더 없음",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index ca6a22e2e..e2895efb9 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -616,7 +616,8 @@ sklm: {
namePlaceholder: "Kaynak adı",
urlHint: "https://…/catalog.json",
documentTooLarge: "Kaynaklar eklendikten sonra bu beceri 128 KB belge sınırını aşıyor.",
- sourceUnsafe: "Kaynak URL'si genel bir https adresi olmalıdır",
+ sourceUnsafe:
+ "Kaynak URL'si http veya https bir adres olmalı, bulut meta veri adresi olmamalıdır. Kendi makinenizde veya LAN'ınızda düz http için Ağ ayarlarında “Kendi yerel ve LAN servislerim için düz HTTP'ye izin ver” seçeneğini açın.",
pageInfo: "Sayfa {{page}} / {{pages}} · {{total}} skill",
pagePrev: "Önceki sayfa",
pageNext: "Sonraki sayfa",
@@ -973,7 +974,8 @@ sklm: {
namePlaceholder: "Kaynak adı",
urlHint: "https://… (kayıt uç noktası veya katalog JSON)",
officialSource: "Resmî kayıt",
- sourceUnsafe: "Kaynak URL'si genel bir https adresi olmalıdır",
+ sourceUnsafe:
+ "Kaynak URL'si http veya https bir adres olmalı, bulut meta veri adresi olmamalıdır. Kendi makinenizde veya LAN'ınızda düz http için Ağ ayarlarında “Kendi yerel ve LAN servislerim için düz HTTP'ye izin ver” seçeneğini açın.",
pageInfo: "Sayfa {{page}} / {{pages}} · {{total}} sunucu",
pagePrev: "Önceki sayfa",
pageNext: "Sonraki sayfa",
@@ -1180,6 +1182,11 @@ sklm: {
proxyTesting: "Deneniyor…",
proxyTestOk: "Bağlandı",
proxyTestFail: "Bağlanılamadı: {{message}}",
+ networkAllowInsecureUserEndpoints: "Kendi yerel ve LAN servislerim için düz HTTP'ye izin ver",
+ networkAllowInsecureUserEndpointsDesc:
+ "Yalnızca kendi girdiğin adresler için geçerlidir: bu makinede veya LAN'ında çalışan bir model servisi, MCP sunucusu ya da pazar kaynağı. LAN adresine HTTPS kullanıyorsan bu anahtar gerekmez.",
+ networkAllowInsecureUserEndpointsWarning:
+ "Düz HTTP şifrelenmez: aynı ağ kesimindeki kişiler bu bağlantıyı ve servisin kabul ettiği kimlik bilgilerini ele geçirebilir.",
defaultsTitle: "Varsayılanlar",
defaultModel: "Varsayılan model",
defaultModelNone: "Hazır AI servisi yok",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 1d8bba741..31b2f70c2 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -610,7 +610,8 @@ sklm: {
namePlaceholder: "源名称",
urlHint: "https://…/catalog.json",
documentTooLarge: "展开相邻资源后超过 128 KB 文档上限,无法安装。",
- sourceUnsafe: "源地址必须是公网 https 地址",
+ sourceUnsafe:
+ "源地址必须是 http/https 地址,且不能指向云元数据之类的地址。要用明文 http 访问自己的本机或局域网服务,请在网络设置里开启“允许对自填的本机/局域网服务使用明文 HTTP”。",
pageInfo: "第 {{page}} / {{pages}} 页 · 共 {{total}} 个",
pagePrev: "上一页",
pageNext: "下一页",
@@ -958,7 +959,8 @@ sklm: {
namePlaceholder: "源名称",
urlHint: "https://…(registry 端点或目录 JSON)",
officialSource: "官方注册表",
- sourceUnsafe: "源地址必须是公网 https 地址",
+ sourceUnsafe:
+ "源地址必须是 http/https 地址,且不能指向云元数据之类的地址。要用明文 http 访问自己的本机或局域网服务,请在网络设置里开启“允许对自填的本机/局域网服务使用明文 HTTP”。",
pageInfo: "第 {{page}} / {{pages}} 页 · 共 {{total}} 个",
pagePrev: "上一页",
pageNext: "下一页",
@@ -1163,6 +1165,11 @@ sklm: {
proxyTesting: "测试中…",
proxyTestOk: "已连接",
proxyTestFail: "无法连接:{{message}}",
+ networkAllowInsecureUserEndpoints: "允许对自填的本机/局域网服务使用明文 HTTP",
+ networkAllowInsecureUserEndpointsDesc:
+ "只影响你自己填写的地址:本机或局域网上的模型服务、MCP 服务器、市场源。用 HTTPS 访问局域网地址不需要开启此项。",
+ networkAllowInsecureUserEndpointsWarning:
+ "明文 HTTP 不加密:同一网段的其他人可能截获这条连接,以及服务所接受的凭据。",
defaultsTitle: "默认项",
defaultModel: "默认模型",
defaultModelNone: "还没有可用的 AI 服务",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 100c9e8e4..2f9ff3ce1 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -610,7 +610,8 @@ sklm: {
namePlaceholder: "源名稱",
urlHint: "https://…/catalog.json",
documentTooLarge: "展開相鄰資源後超過 128 KB 文件上限,無法安裝。",
- sourceUnsafe: "源位址必須是公網 https 位址",
+ sourceUnsafe:
+ "源位址必須是 http/https 位址,且不能指向雲端中繼資料之類的位址。要用明文 http 存取自己的本機或區域網路服務,請在網路設定中開啟「允許對自填的本機/區域網路服務使用明文 HTTP」。",
pageInfo: "第 {{page}} / {{pages}} 頁 · 共 {{total}} 個",
pagePrev: "上一頁",
pageNext: "下一頁",
@@ -958,7 +959,8 @@ sklm: {
namePlaceholder: "源名稱",
urlHint: "https://…(registry 端點或目錄 JSON)",
officialSource: "官方註冊表",
- sourceUnsafe: "源位址必須是公網 https 位址",
+ sourceUnsafe:
+ "源位址必須是 http/https 位址,且不能指向雲端中繼資料之類的位址。要用明文 http 存取自己的本機或區域網路服務,請在網路設定中開啟「允許對自填的本機/區域網路服務使用明文 HTTP」。",
pageInfo: "第 {{page}} / {{pages}} 頁 · 共 {{total}} 個",
pagePrev: "上一頁",
pageNext: "下一頁",
@@ -1163,6 +1165,11 @@ sklm: {
proxyTesting: "測試中…",
proxyTestOk: "已連線",
proxyTestFail: "無法連線:{{message}}",
+ networkAllowInsecureUserEndpoints: "允許對自填的本機/區域網路服務使用明文 HTTP",
+ networkAllowInsecureUserEndpointsDesc:
+ "只影響你自己填寫的位址:本機或區域網路上的模型服務、MCP 伺服器、市場來源。用 HTTPS 存取區域網路位址不需要開啟此項。",
+ networkAllowInsecureUserEndpointsWarning:
+ "明文 HTTP 不加密:同一網段的其他使用者可能截獲這條連線,以及服務所接受的憑證。",
defaultsTitle: "預設項",
defaultModel: "預設模型",
defaultModelNone: "還沒有可用的 AI 服務",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 6d4a8b34b..369d0a7cf 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -32,6 +32,7 @@ export {
type SourcedCatalogEntry,
} from "./mcp-registry.js";
export * from "./public-network.js";
+export * from "./network-policy.js";
export * from "./skill-catalog.js";
export * from "./skill-catalog-builtin.js";
export * from "./model-config-import.js";
diff --git a/packages/shared/src/mcp-registry.test.ts b/packages/shared/src/mcp-registry.test.ts
index 800697ec5..98849ce60 100644
--- a/packages/shared/src/mcp-registry.test.ts
+++ b/packages/shared/src/mcp-registry.test.ts
@@ -419,20 +419,65 @@ describe("registry argument and env semantics", () => {
});
});
-describe("isPublicHostname / isPublicIpLiteral edge cases", () => {
- it("rejects trailing-dot and smuggeled private hosts", () => {
- expect(isSafeMarketSourceUrl("https://localhost./x")).toBe(false);
+describe("isSafeMarketSourceUrl (a source URL the user typed)", () => {
+ it("accepts a source the user runs on loopback, the LAN, or their own host", () => {
+ // The market source is an address the person in front of the app typed in,
+ // so their own machine and their own LAN are reachable. Every URL that
+ // arrives *inside* a catalog stays on the public-only policy instead
+ // (`validateMcpCatalogFile`, and the redirect the main-process client
+ // re-validates per hop).
+ expect(isSafeMarketSourceUrl("https://127.0.0.1/x")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://10.1.2.3/x")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://192.168.1.5:8443/x")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://localhost./x")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://nas.local/x")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://[::1]/")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://[::ffff:127.0.0.1]/")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://[fd00::1]/")).toBe(true);
+ expect(isSafeMarketSourceUrl("https://[fe80::1]/")).toBe(true);
expect(isSafeMarketSourceUrl("https://localhost.example./x")).toBe(true); // public dot-FQDN ok
- expect(isSafeMarketSourceUrl("https://[::ffff:127.0.0.1]/")).toBe(false);
- expect(isSafeMarketSourceUrl("https://[fd00::1]/")).toBe(false);
- expect(isSafeMarketSourceUrl("https://[fe80::1]/")).toBe(false);
- expect(isSafeMarketSourceUrl("https://[::1]/")).toBe(false);
- expect(isSafeMarketSourceUrl("https://127.0.0.1/x")).toBe(false);
- expect(isSafeMarketSourceUrl("https://10.1.2.3/x")).toBe(false);
- expect(isSafeMarketSourceUrl("https://[2001:db8::1]/")).toBe(false);
expect(isSafeMarketSourceUrl("https://[2606:4700::1]/")).toBe(true);
expect(isSafeMarketSourceUrl("https://registry.example/x")).toBe(true);
});
+
+ it("still refuses the classes that name no service the user could mean", () => {
+ expect(isSafeMarketSourceUrl("https://0.0.0.0/x")).toBe(false); // unspecified
+ expect(isSafeMarketSourceUrl("https://239.1.2.3/x")).toBe(false); // multicast
+ expect(isSafeMarketSourceUrl("https://240.0.0.1/x")).toBe(false); // reserved
+ expect(isSafeMarketSourceUrl("https://192.0.2.1/x")).toBe(false); // documentation
+ expect(isSafeMarketSourceUrl("https://[2001:db8::1]/")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://[2002::1]/")).toBe(false); // 6to4
+ expect(isSafeMarketSourceUrl("not a url")).toBe(false);
+ expect(isSafeMarketSourceUrl("file:///etc/passwd")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://user:[email protected]/x")).toBe(false);
+ });
+
+ it("refuses every cloud metadata endpoint on a settings field", () => {
+ // A metadata service answers with the host's own credentials, so a source
+ // URL naming one is an injected SSRF payload far more often than it is a
+ // catalog the user runs.
+ expect(isSafeMarketSourceUrl("https://169.254.169.254/x")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://169.254.169.254./x")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://100.100.100.200/x")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://[fd00:ec2::254]/x")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://metadata.google.internal/x")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://metadata./x")).toBe(false);
+ expect(isSafeMarketSourceUrl("https://instance-data/x")).toBe(false);
+ });
+
+ it("wants the stored opt-in before a plaintext source is accepted", () => {
+ expect(isSafeMarketSourceUrl("http://10.0.0.7:8080/catalog.json")).toBe(false);
+ expect(
+ isSafeMarketSourceUrl("http://10.0.0.7:8080/catalog.json", { allowInsecureHttp: true }),
+ ).toBe(true);
+ // `https` to the user's own LAN needs no opt-in, and the flag is the only
+ // thing that changes: it never loosens a class or a metadata host.
+ expect(isSafeMarketSourceUrl("https://10.0.0.7:8443/catalog.json")).toBe(true);
+ expect(
+ isSafeMarketSourceUrl("http://169.254.169.254/x", { allowInsecureHttp: true }),
+ ).toBe(false);
+ expect(isSafeMarketSourceUrl("http://registry.example/x", { allowInsecureHttp: true })).toBe(true);
+ });
});
describe("sanitizeMarketSources", () => {
@@ -462,4 +507,30 @@ describe("sanitizeMarketSources", () => {
]),
).toHaveLength(1);
});
+
+ it("keeps a LAN source, and a plaintext one only under the opt-in", () => {
+ const lan = {
+ id: "lan",
+ name: "LAN",
+ url: "https://192.168.1.5:8443/catalog.json",
+ kind: "catalog" as const,
+ };
+ const plaintext = {
+ id: "plain",
+ name: "Plain",
+ url: "http://10.0.0.7:8080/catalog.json",
+ kind: "catalog" as const,
+ };
+ const metadata = {
+ id: "meta",
+ name: "Meta",
+ url: "https://169.254.169.254/catalog.json",
+ kind: "catalog" as const,
+ };
+ const ids = (list: ReturnType<typeof sanitizeMarketSources>) => list.map((source) => source.id);
+ expect(ids(sanitizeMarketSources([lan, plaintext, metadata]))).toEqual(["official", "lan"]);
+ expect(
+ ids(sanitizeMarketSources([lan, plaintext, metadata], { allowInsecureHttp: true })),
+ ).toEqual(["official", "lan", "plain"]);
+ });
});
diff --git a/packages/shared/src/mcp-registry.ts b/packages/shared/src/mcp-registry.ts
index ae579a7d2..979ec4141 100644
--- a/packages/shared/src/mcp-registry.ts
+++ b/packages/shared/src/mcp-registry.ts
@@ -14,7 +14,7 @@ import {
type McpCatalogHeaderBinding,
type McpCatalogRequiredEnv,
} from "./mcp-catalog.js";
-import { isPublicHttpsUrl } from "./public-network.js";
+import { isPublicHttpsUrl, isSafeUserEndpointUrl } from "./public-network.js";
export { isPublicHostname, isPublicIpLiteral } from "./public-network.js";
export type RegistryEnvVar = {
@@ -352,18 +352,29 @@ export const DEFAULT_MARKET_SOURCE: MarketSource = {
const MAX_MARKET_SOURCES = 16;
/**
- * Guard for user-entered source URLs. The same credentials-free public HTTPS
- * policy is used by renderer validation and by main-process requests.
+ * Guard for a source URL the user entered.
+ *
+ * The user typed this address, so it may be a LAN or loopback catalog under the
+ * stored `networkPolicy`; plain `http` needs the explicit opt-in. Everything a
+ * source *returns* — a registry record, a catalog body, a redirect target — is
+ * judged by the third-party policy instead, so loosening this guard never
+ * widens the boundary for content the app did not receive from the user.
*/
-export function isSafeMarketSourceUrl(url: string): boolean {
- return isPublicHttpsUrl(url);
+export function isSafeMarketSourceUrl(
+ url: string,
+ options: { allowInsecureHttp?: boolean } = {},
+): boolean {
+ return isSafeUserEndpointUrl(url, options);
}
/** A catalog entry tagged with the source that produced it. */
export type SourcedCatalogEntry = McpCatalogEntry & { sourceId: string };
/** Repair whatever the renderer persisted into a usable source list. */
-export function sanitizeMarketSources(value: unknown): MarketSource[] {
+export function sanitizeMarketSources(
+ value: unknown,
+ options: { allowInsecureHttp?: boolean } = {},
+): MarketSource[] {
const raw = Array.isArray(value) ? value : [];
const seen = new Set<string>();
const sources: MarketSource[] = [];
@@ -376,7 +387,7 @@ export function sanitizeMarketSources(value: unknown): MarketSource[] {
typeof candidate.name !== "string" ||
typeof candidate.url !== "string" ||
(candidate.kind !== "registry" && candidate.kind !== "catalog") ||
- !isSafeMarketSourceUrl(candidate.url) ||
+ !isSafeMarketSourceUrl(candidate.url, options) ||
seen.has(candidate.id)
) {
continue;
diff --git a/packages/shared/src/network-policy.test.ts b/packages/shared/src/network-policy.test.ts
new file mode 100644
index 000000000..fe1d63709
--- /dev/null
+++ b/packages/shared/src/network-policy.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+import {
+ DEFAULT_NETWORK_POLICY,
+ allowInsecureUserEndpoints,
+ normalizeNetworkPolicy,
+ validateNetworkPolicy,
+} from "./network-policy.js";
+
+describe("normalizeNetworkPolicy", () => {
+ it("keeps the opt-in and drops everything else", () => {
+ expect(normalizeNetworkPolicy({ allowInsecureUserEndpoints: true })).toEqual({
+ allowInsecureUserEndpoints: true,
+ });
+ expect(normalizeNetworkPolicy({ allowInsecureUserEndpoints: false })).toEqual({});
+ expect(normalizeNetworkPolicy({ allowInsecureUserEndpoints: "yes" })).toEqual({});
+ expect(normalizeNetworkPolicy({ somethingElse: true })).toEqual({});
+ expect(normalizeNetworkPolicy(null)).toEqual({});
+ expect(normalizeNetworkPolicy(undefined)).toEqual({});
+ });
+
+ it("defaults to refusing the plaintext case", () => {
+ expect(DEFAULT_NETWORK_POLICY.allowInsecureUserEndpoints).toBe(false);
+ });
+});
+
+describe("validateNetworkPolicy", () => {
+ it("accepts an absent section, a boolean and an empty object", () => {
+ expect(validateNetworkPolicy(undefined)).toEqual({
+ ok: true,
+ value: { allowInsecureUserEndpoints: false },
+ });
+ expect(validateNetworkPolicy({})).toEqual({ ok: true, value: {} });
+ expect(validateNetworkPolicy({ allowInsecureUserEndpoints: true })).toEqual({
+ ok: true,
+ value: { allowInsecureUserEndpoints: true },
+ });
+ });
+
+ it("refuses a non-object or a non-boolean flag", () => {
+ expect(validateNetworkPolicy([]).ok).toBe(false);
+ expect(validateNetworkPolicy("networkPolicy").ok).toBe(false);
+ expect(validateNetworkPolicy({ allowInsecureUserEndpoints: 1 }).ok).toBe(false);
+ expect(validateNetworkPolicy({ allowInsecureUserEndpoints: null }).ok).toBe(false);
+ });
+});
+
+describe("allowInsecureUserEndpoints", () => {
+ it("reads the networkPolicy section of a settings object", () => {
+ expect(
+ allowInsecureUserEndpoints({ networkPolicy: { allowInsecureUserEndpoints: true } }),
+ ).toBe(true);
+ expect(
+ allowInsecureUserEndpoints({ networkPolicy: { allowInsecureUserEndpoints: false } }),
+ ).toBe(false);
+ expect(allowInsecureUserEndpoints({})).toBe(false);
+ expect(allowInsecureUserEndpoints(null)).toBe(false);
+ expect(allowInsecureUserEndpoints({ networkPolicy: "yes" })).toBe(false);
+ });
+
+ it("ignores a top-level lookalike key", () => {
+ // Only the section is read: the host validates that one on write, and a
+ // stray top-level field is not something any surface sets.
+ expect(allowInsecureUserEndpoints({ allowInsecureUserEndpoints: true })).toBe(false);
+ expect(allowInsecureUserEndpoints({ networkPolicy: { allowInsecure: true } })).toBe(false);
+ });
+});
diff --git a/packages/shared/src/network-policy.ts b/packages/shared/src/network-policy.ts
new file mode 100644
index 000000000..a846c6a45
--- /dev/null
+++ b/packages/shared/src/network-policy.ts
@@ -0,0 +1,85 @@
+/**
+ * Trust policy for the network endpoints a user enters themselves.
+ *
+ * Address judgement lives in `public-network.ts`, which answers "is this
+ * address public?". This module answers the separate question the app asks
+ * before it applies that judgement: "did the user type this endpoint in
+ * themselves, and did they accept the plaintext case for it?".
+ *
+ * Endpoints the user typed — a model base URL, an MCP server, a market source,
+ * a git remote, a WebDAV root — are that person's own choice, so the guard
+ * treats loopback and LAN addresses as reachable. Content the app did not
+ * receive from the user — a registry record, a market catalog body, an HTTP
+ * redirect target — keeps the strict public-network policy, because that is
+ * where the SSRF risk lives.
+ */
+
+/**
+ * Who chose the address one request is judged for.
+ *
+ * `user` is an endpoint the person typed into a settings field: their own
+ * machine, their own LAN service, their own public server. `third-party` is
+ * everything the app did not receive from them — a redirect target, a catalog
+ * body, a registry record — which keeps the strict public-network policy,
+ * because that is the input an attacker controls.
+ */
+export type EndpointOrigin = "user" | "third-party";
+
+/** `settings.networkPolicy`. */
+export type NetworkPolicySettings = {
+ /**
+ * Permit plain `http` for a user-supplied endpoint. Off by default: on a LAN
+ * a plaintext hop carries whatever credentials that endpoint accepts, so it
+ * stays the user's explicit call rather than a default (the shape ADR 0300
+ * uses for a WebDAV endpoint).
+ */
+ allowInsecureUserEndpoints?: boolean;
+};
+
+export const DEFAULT_NETWORK_POLICY: NetworkPolicySettings = {
+ allowInsecureUserEndpoints: false,
+};
+
+/** Keep only the fields this policy defines, with their usable values. */
+export function normalizeNetworkPolicy(value: unknown): NetworkPolicySettings {
+ const record =
+ value && typeof value === "object" ? (value as Record<string, unknown>) : {};
+ const next: NetworkPolicySettings = {};
+ if (record.allowInsecureUserEndpoints === true) {
+ next.allowInsecureUserEndpoints = true;
+ }
+ return next;
+}
+
+export type ValidateNetworkPolicyResult =
+ | { ok: true; value: NetworkPolicySettings }
+ | { ok: false; error: string };
+
+export function validateNetworkPolicy(value: unknown): ValidateNetworkPolicyResult {
+ if (value === undefined || value === null) {
+ return { ok: true, value: { ...DEFAULT_NETWORK_POLICY } };
+ }
+ if (typeof value !== "object" || Array.isArray(value)) {
+ return { ok: false, error: "networkPolicy must be an object" };
+ }
+ const flag = (value as Record<string, unknown>).allowInsecureUserEndpoints;
+ if (flag !== undefined && typeof flag !== "boolean") {
+ return { ok: false, error: "allowInsecureUserEndpoints must be a boolean" };
+ }
+ return { ok: true, value: normalizeNetworkPolicy(value) };
+}
+
+/**
+ * Read the plaintext opt-in out of a whole settings object.
+ *
+ * Only the `networkPolicy` section is read. A top-level lookalike key must not
+ * be able to turn the opt-in on: the host validates this section on write, and
+ * any other spelling of the flag is a field nothing sets.
+ */
+export function allowInsecureUserEndpoints(settings: unknown): boolean {
+ const section =
+ settings && typeof settings === "object"
+ ? (settings as { networkPolicy?: unknown }).networkPolicy
+ : undefined;
+ return normalizeNetworkPolicy(section).allowInsecureUserEndpoints === true;
+}
diff --git a/packages/shared/src/network-proxy.test.ts b/packages/shared/src/network-proxy.test.ts
index 49e907666..ce09f6a9b 100644
--- a/packages/shared/src/network-proxy.test.ts
+++ b/packages/shared/src/network-proxy.test.ts
@@ -154,17 +154,28 @@ describe("chromium and env projections", () => {
}).HTTP_PROXY).toBe("http://user:[email protected]:8080");
});
- it("omits Chromium <local> from NO_PROXY and does not set HTTP_PROXY for SOCKS", () => {
+ it("omits Chromium <local> from NO_PROXY, keeps the LAN ranges, and does not set HTTP_PROXY for SOCKS", () => {
+ // The default bypass is the user's own machine plus the private ranges a
+ // user's LAN devices live in: a proxy is for reaching the public internet,
+ // and sending a local model server, NAS or MCP endpoint through it is how it
+ // stops answering. `<local>` is Chromium's own single-label rule rather than
+ // an env-var wildcard, so NO_PROXY drops it and keeps everything else.
+ const lanRanges = "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16";
+ const envBypass = `localhost,127.0.0.1,::1,${lanRanges}`;
+ // Pinned literally: `crates/host-core/src/network_proxy.rs` carries the same
+ // string for the sidecar's own bypass.
+ expect(DEFAULT_NETWORK_PROXY_BYPASS).toBe(
+ `localhost,127.0.0.1,::1,<local>,${lanRanges}`,
+ );
const socks = proxyEnvAssignments({
mode: "custom",
url: "socks5://127.0.0.1:1080",
});
expect(socks.ALL_PROXY).toBe("socks5://127.0.0.1:1080");
expect(socks.HTTP_PROXY).toBeNull();
- expect(socks.NO_PROXY).toBe("localhost,127.0.0.1,::1");
- expect(envProxyBypass({ mode: "custom", url: "http://127.0.0.1:7890" })).toBe(
- "localhost,127.0.0.1,::1",
- );
+ expect(socks.NO_PROXY).toBe(envBypass);
+ expect(socks.NO_PROXY ?? "").not.toContain("<local>");
+ expect(envProxyBypass({ mode: "custom", url: "http://127.0.0.1:7890" })).toBe(envBypass);
const http = proxyEnvAssignments({
mode: "custom",
diff --git a/packages/shared/src/network-proxy.ts b/packages/shared/src/network-proxy.ts
index 763640a90..bd2c29eec 100644
--- a/packages/shared/src/network-proxy.ts
+++ b/packages/shared/src/network-proxy.ts
@@ -18,8 +18,16 @@ export const NETWORK_PROXY_SCHEMES = [
] as const;
export type NetworkProxyScheme = (typeof NETWORK_PROXY_SCHEMES)[number];
+/**
+ * Default bypass list for custom mode.
+ *
+ * Loopback plus the private ranges a user's own LAN devices live in. A proxy is
+ * for reaching the public internet; sending `192.168.0.0/16` through it is how
+ * a local model server, NAS or MCP endpoint stops answering. `<local>` keeps
+ * Chromium's own single-label rule.
+ */
export const DEFAULT_NETWORK_PROXY_BYPASS =
- "localhost,127.0.0.1,::1,<local>";
+ "localhost,127.0.0.1,::1,<local>,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16";
export const PROXY_ENV_KEYS = [
"HTTP_PROXY",
diff --git a/packages/shared/src/public-network.test.ts b/packages/shared/src/public-network.test.ts
index 3a2f693be..2910be01f 100644
--- a/packages/shared/src/public-network.test.ts
+++ b/packages/shared/src/public-network.test.ts
@@ -4,16 +4,20 @@ import {
classifyIpLiteral,
classifyProxyRoute,
isAcceptableResolvedAddress,
+ isAcceptableUserEndpointAddress,
+ isCloudMetadataAddress,
+ isCloudMetadataHost,
isPublicHttpsUrl,
isPublicIpLiteral,
PUBLIC_NETWORK_POLICY_ERROR,
isPublicHostname,
isProxyFakeIpAddress,
isPublicNetworkPolicyFailure,
+ isSafeUserEndpointUrl,
+ isUserSuppliedHostname,
publicNetworkRefusalDetail,
publicNetworkRefusalReason,
} from "./public-network.js";
-
describe("public network address policy", () => {
it("classifies special-use IPv4 ranges", () => {
const cases: Array<[string, ReturnType<typeof classifyIpLiteral>]> = [
@@ -258,3 +262,128 @@ describe("public network address policy", () => {
).toEqual({ reason: "url-syntax", route: "proxied" });
});
});
+
+/**
+ * The question these helpers answer is "did the user type this endpoint in
+ * themselves?". Their own machine and their own LAN are that person's own
+ * choice; the classes that name no destination at all, and cloud metadata, stay
+ * refused on every input.
+ */
+describe("user-supplied endpoint policy", () => {
+ it("accepts loopback, LAN and local DNS names a user typed in", () => {
+ for (const host of [
+ "localhost",
+ "127.0.0.1",
+ "10.1.2.3",
+ "172.16.0.1",
+ "192.168.1.5",
+ "100.64.0.1",
+ "169.254.10.20",
+ "nas.local",
+ "dev.internal",
+ "::1",
+ "[fd00::1]",
+ "[fe80::1]",
+ "[fec0::1]",
+ "example.com",
+ "[2606:4700::1]",
+ ]) {
+ expect(isUserSuppliedHostname(host), host).toBe(true);
+ }
+ });
+
+ it("refuses the classes that name no destination, and cloud metadata", () => {
+ for (const host of [
+ "0.0.0.0",
+ "::",
+ "224.0.0.1",
+ "240.0.0.1",
+ "192.0.2.1",
+ "[2001:db8::1]",
+ "169.254.169.254",
+ "100.100.100.200",
+ "[fd00:ec2::254]",
+ "metadata.google.internal",
+ "metadata",
+ "instance-data",
+ "169.254.169.254.",
+ "",
+ ]) {
+ expect(isUserSuppliedHostname(host), host).toBe(false);
+ }
+ });
+
+ it("classifies a user-supplied address by kind and route", () => {
+ for (const kind of [
+ "public",
+ "loopback",
+ "private",
+ "cgnat",
+ "link-local",
+ "ula",
+ "site-local",
+ ] as const) {
+ expect(isAcceptableUserEndpointAddress("192.168.1.5", kind, "direct"), kind).toBe(true);
+ expect(isAcceptableUserEndpointAddress("192.168.1.5", kind, "proxied"), kind).toBe(true);
+ }
+ for (const kind of [
+ "invalid",
+ "unspecified",
+ "multicast",
+ "reserved",
+ "documentation",
+ ] as const) {
+ expect(isAcceptableUserEndpointAddress("192.168.1.5", kind, "direct"), kind).toBe(false);
+ }
+ // A TUN fake-IP answer is the proxy's placeholder for the name, so it is
+ // tolerated only when this app dials a proxy instead of that address
+ // (ADR 0272).
+ expect(isAcceptableUserEndpointAddress("192.168.1.5", "benchmark", "proxied")).toBe(true);
+ expect(isAcceptableUserEndpointAddress("192.168.1.5", "benchmark", "direct")).toBe(false);
+ // The address itself can still veto the verdict: a cloud metadata endpoint
+ // is refused whichever class it was read as.
+ expect(isAcceptableUserEndpointAddress("169.254.169.254", "link-local", "direct")).toBe(false);
+ // Including an IPv4-mapped spelling of it.
+ expect(
+ isAcceptableUserEndpointAddress("::ffff:169.254.169.254", "link-local", "direct"),
+ ).toBe(false);
+ });
+
+ it("requires the explicit opt-in for a plaintext user endpoint", () => {
+ expect(isSafeUserEndpointUrl("https://192.168.1.5:8443/catalog.json")).toBe(true);
+ expect(isSafeUserEndpointUrl("https://127.0.0.1/catalog.json")).toBe(true);
+ expect(isSafeUserEndpointUrl("http://192.168.1.5:8080/catalog.json")).toBe(false);
+ expect(
+ isSafeUserEndpointUrl("http://192.168.1.5:8080/catalog.json", { allowInsecureHttp: true }),
+ ).toBe(true);
+ expect(isSafeUserEndpointUrl("https://user:[email protected]/catalog.json")).toBe(false);
+ expect(isSafeUserEndpointUrl("https://169.254.169.254/latest/meta-data")).toBe(false);
+ expect(
+ isSafeUserEndpointUrl("https://169.254.169.254/x", { allowInsecureHttp: true }),
+ ).toBe(false);
+ expect(isSafeUserEndpointUrl("ftp://192.168.1.5/catalog.json", { allowInsecureHttp: true })).toBe(
+ false,
+ );
+ expect(isSafeUserEndpointUrl("not a url")).toBe(false);
+ });
+
+ it("names cloud metadata hosts and addresses, however they are spelled", () => {
+ expect(isCloudMetadataAddress("169.254.169.254")).toBe(true);
+ expect(isCloudMetadataAddress("100.100.100.200")).toBe(true);
+ expect(isCloudMetadataAddress("fd00:ec2::254")).toBe(true);
+ expect(isCloudMetadataAddress("[fd00:ec2::254]")).toBe(true);
+ expect(isCloudMetadataAddress("fd00:ec2:0:0:0:0:0:254")).toBe(true);
+ expect(isCloudMetadataAddress("::ffff:169.254.169.254")).toBe(true);
+ expect(isCloudMetadataAddress("::ffff:a9fe:a9fe")).toBe(true);
+ expect(isCloudMetadataAddress("::169.254.169.254")).toBe(true);
+ expect(isCloudMetadataAddress("::ffff:10.0.0.8")).toBe(false);
+ expect(isCloudMetadataAddress("10.0.0.8")).toBe(false);
+ expect(isCloudMetadataAddress("169.254.10.20")).toBe(false);
+ expect(isCloudMetadataHost("metadata.google.internal.")).toBe(true);
+ expect(isCloudMetadataHost("METADATA")).toBe(true);
+ expect(isCloudMetadataHost("instance-data")).toBe(true);
+ expect(isCloudMetadataHost("::ffff:169.254.169.254")).toBe(true);
+ expect(isCloudMetadataHost("metadata.example.com")).toBe(false);
+ expect(isCloudMetadataHost("localhost")).toBe(false);
+ });
+});
diff --git a/packages/shared/src/public-network.ts b/packages/shared/src/public-network.ts
index c0ee4919c..6c4868def 100644
--- a/packages/shared/src/public-network.ts
+++ b/packages/shared/src/public-network.ts
@@ -137,6 +137,194 @@ export function isPublicHttpsUrl(value: string): boolean {
/** Backward-compatible descriptive alias for the generic public URL guard. */
export const isSafePublicHttpsUrl = isPublicHttpsUrl;
+/**
+ * Cloud instance-metadata services answer with the host's own credentials, so
+ * no user-supplied endpoint may name one: a settings field carrying such an
+ * address is an injected SSRF payload far more often than it is a service the
+ * user runs themselves.
+ */
+const CLOUD_METADATA_HOSTNAMES = new Set([
+ "metadata.google.internal",
+ "metadata",
+ "instance-data",
+]);
+
+const CLOUD_METADATA_ADDRESSES = new Set([
+ "169.254.169.254",
+ "100.100.100.200",
+ "fd00:ec2::254",
+]);
+
+/** A hostname with its brackets, trailing dot and case normalized away. */
+function bareHostname(value: string): string {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/^\[/, "")
+ .replace(/\]$/, "")
+ .replace(/\.+$/, "");
+}
+
+/** Whether a hostname names a cloud instance-metadata service. */
+export function isCloudMetadataHost(hostname: string): boolean {
+ if (typeof hostname !== "string") return false;
+ const host = bareHostname(hostname);
+ return CLOUD_METADATA_HOSTNAMES.has(host) || isCloudMetadataAddress(host);
+}
+
+/** The dotted-quad spelling of a 32-bit IPv4 address. */
+function dottedIpv4(value: number): string {
+ return [value >>> 24, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff].join(".");
+}
+
+/**
+ * Whether an IP literal names a cloud instance-metadata service.
+ *
+ * The comparison runs on the address a literal *means*, never on its spelling:
+ * `::ffff:169.254.169.254`, `::ffff:a9fe:a9fe` and `::169.254.169.254` all name
+ * the IPv4 metadata service, and `fd00:ec2:0:0:0:0:0:254` is the same address as
+ * `fd00:ec2::254`. A spelling this guard failed to recognize would be a way to
+ * reach the host's own credentials, so every equivalent form is folded here.
+ */
+export function isCloudMetadataAddress(address: string): boolean {
+ if (typeof address !== "string") return false;
+ const host = bareHostname(address);
+ if (!host) return false;
+ if (CLOUD_METADATA_ADDRESSES.has(host)) return true;
+
+ const ipv4 = parseIpv4(host);
+ if (ipv4 !== null) return CLOUD_METADATA_ADDRESSES.has(dottedIpv4(ipv4));
+
+ const ipv6 = parseIpv6(host);
+ if (!ipv6) return false;
+ const { groups } = ipv6;
+ // AWS's IPv6 metadata address, in any spelling.
+ if (
+ groups[0] === 0xfd00 &&
+ groups[1] === 0x0ec2 &&
+ groups[7] === 0x0254 &&
+ groups.slice(2, 7).every((group) => group === 0)
+ ) {
+ return true;
+ }
+ // IPv4-mapped and IPv4-compatible literals carry the IPv4 address itself.
+ if (
+ groups.slice(0, 5).every((group) => group === 0) &&
+ (groups[5] === 0 || groups[5] === 0xffff)
+ ) {
+ return CLOUD_METADATA_ADDRESSES.has(dottedIpv4(groups[6] * 0x10000 + groups[7]));
+ }
+ return false;
+}
+
+/**
+ * Address classes a *user-supplied* endpoint may reach.
+ *
+ * The public-network guard exists to stop third-party content — a market
+ * catalog, a registry record, a redirect — from turning this app into a probe
+ * of the machine's own network. A host the user typed in themselves is a
+ * different trust input: a model endpoint, an MCP server, a market source URL
+ * and a git remote are all chosen by the person sitting in front of the app,
+ * who already knows that machine. Refusing those addresses pushes the same work
+ * outside the app without removing the request, so loopback, RFC1918, CGNAT,
+ * link-local, ULA and site-local are reachable here.
+ *
+ * The classes that name no destination at all (`unspecified`, `multicast`,
+ * `reserved`, `documentation`, `invalid`) and cloud metadata stay refused on
+ * every input, because none of them is a service the user could mean.
+ */
+export function isAcceptableUserEndpointAddress(
+ address: string,
+ kind: PublicNetworkAddressKind,
+ route: PublicNetworkRoute,
+): boolean {
+ if (isCloudMetadataAddress(address)) return false;
+ switch (kind) {
+ case "public":
+ case "loopback":
+ case "private":
+ case "cgnat":
+ case "link-local":
+ case "ula":
+ case "site-local":
+ return true;
+ case "benchmark":
+ // A TUN fake-IP answer on a proxied route is the proxy's own placeholder
+ // rather than an address this app dials (ADR 0272); on a direct route it
+ // still names no reachable service.
+ return route === "proxied";
+ default:
+ return false;
+ }
+}
+
+/**
+ * Check a user-supplied endpoint hostname without performing DNS. Literal
+ * addresses are classified directly; a DNS name is syntactically acceptable and
+ * the address it resolves to is judged by
+ * {@link isAcceptableUserEndpointAddress}.
+ */
+export function isUserSuppliedHostname(hostname: string): boolean {
+ if (typeof hostname !== "string") return false;
+ const host = bareHostname(hostname);
+ if (!host) return false;
+ if (isCloudMetadataHost(host)) return false;
+
+ if (host.includes(":")) {
+ return isAcceptableUserEndpointAddress(host, classifyIpLiteral(host), "direct");
+ }
+ const literal = parseIpv4(host);
+ if (literal !== null) {
+ return isAcceptableUserEndpointAddress(host, classifyIpv4(literal), "direct");
+ }
+ // WHATWG URL normalizes legacy numeric IPv4 forms (decimal, hexadecimal and
+ // shortened dotted forms) before exposing `hostname`. Keep a hostname handed
+ // in directly consistent with one that came out of `new URL(...).hostname`.
+ if (/^[0-9a-fx.]+$/i.test(host)) {
+ try {
+ const normalized = bareHostname(new URL(`https://${host}`).hostname);
+ if (normalized !== host) {
+ const normalizedLiteral = parseIpv4(normalized);
+ if (normalizedLiteral !== null) {
+ return isAcceptableUserEndpointAddress(
+ normalized,
+ classifyIpv4(normalizedLiteral),
+ "direct",
+ );
+ }
+ }
+ } catch {
+ return false;
+ }
+ }
+ return true;
+}
+
+/**
+ * Check a credentials-free URL whose host the user entered themselves.
+ *
+ * `http` is accepted only under an explicit opt-in, because on a LAN it is an
+ * unencrypted hop that carries whatever credentials the endpoint takes — the
+ * same shape ADR 0300 uses for a WebDAV endpoint. `https` to a private host
+ * needs no opt-in: the transport is still protected, and the address is the
+ * user's own choice.
+ */
+export function isSafeUserEndpointUrl(
+ value: string,
+ options: { allowInsecureHttp?: boolean } = {},
+): boolean {
+ if (typeof value !== "string") return false;
+ let parsed: URL;
+ try {
+ parsed = new URL(value);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return false;
+ if (parsed.protocol === "http:" && options.allowInsecureHttp !== true) return false;
+ if (parsed.username || parsed.password) return false;
+ return isUserSuppliedHostname(parsed.hostname);
+}
/**
* The route the transport will actually take for a URL, as the Chromium session
diff --git a/packages/shared/src/skill-catalog.test.ts b/packages/shared/src/skill-catalog.test.ts
index 7b66d1ce6..3b301df91 100644
--- a/packages/shared/src/skill-catalog.test.ts
+++ b/packages/shared/src/skill-catalog.test.ts
@@ -3,8 +3,10 @@ import { BUILTIN_SKILL_CATALOG } from "./skill-catalog-builtin.js";
import {
assembleSkillInstall,
expandSkillResources,
+ isSafeSkillSourceUrl,
MAX_SKILL_DOCUMENT_BYTES,
sanitizeSkillCatalogId,
+ sanitizeSkillSources,
skillEntryError,
splitSkillDocument,
toSkillInput,
@@ -150,3 +152,65 @@ describe("assembleSkillInstall", () => {
expect(assembled.bytes).toBeGreaterThan(MAX_SKILL_DOCUMENT_BYTES);
});
});
+
+/**
+ * A skill market source URL is an address the user typed into a settings field,
+ * so their own machine and their own LAN are reachable. A document URL that
+ * arrives *inside* a catalog is content the app did not receive from them and
+ * keeps the public-only policy in `skill-market-scan.ts` instead.
+ */
+describe("skill market source URLs", () => {
+ it("accepts a source the user runs on loopback or the LAN", () => {
+ expect(isSafeSkillSourceUrl("https://127.0.0.1/catalog.json")).toBe(true);
+ expect(isSafeSkillSourceUrl("https://192.168.1.5:8443/catalog.json")).toBe(true);
+ expect(isSafeSkillSourceUrl("https://nas.local/catalog.json")).toBe(true);
+ expect(isSafeSkillSourceUrl("https://[fd00::1]/catalog.json")).toBe(true);
+ expect(isSafeSkillSourceUrl("https://cdn.jsdelivr.net/gh/x/SKILL.md")).toBe(true);
+ });
+
+ it("keeps the classes that name no service, and cloud metadata, refused", () => {
+ expect(isSafeSkillSourceUrl("https://169.254.169.254/catalog.json")).toBe(false);
+ expect(isSafeSkillSourceUrl("https://100.100.100.200/catalog.json")).toBe(false);
+ expect(isSafeSkillSourceUrl("https://metadata.google.internal/catalog.json")).toBe(false);
+ expect(isSafeSkillSourceUrl("https://[2001:db8::1]/catalog.json")).toBe(false);
+ expect(isSafeSkillSourceUrl("https://user:[email protected]/catalog.json")).toBe(false);
+ expect(isSafeSkillSourceUrl("file:///etc/passwd")).toBe(false);
+ });
+
+ it("wants the stored opt-in before a plaintext source is accepted", () => {
+ expect(isSafeSkillSourceUrl("http://10.0.0.7:8080/catalog.json")).toBe(false);
+ expect(
+ isSafeSkillSourceUrl("http://10.0.0.7:8080/catalog.json", { allowInsecureHttp: true }),
+ ).toBe(true);
+ // The opt-in is the only thing the flag buys: it never admits a class the
+ // user could not have meant.
+ expect(
+ isSafeSkillSourceUrl("http://169.254.169.254/catalog.json", { allowInsecureHttp: true }),
+ ).toBe(false);
+ });
+
+ it("repairs a persisted source list under the same policy", () => {
+ const ids = (list: ReturnType<typeof sanitizeSkillSources>) =>
+ list.map((source) => source.id);
+ expect(
+ ids(
+ sanitizeSkillSources([
+ { id: "lan", name: "LAN", url: "https://192.168.1.5:8443/catalog.json" },
+ { id: "meta", name: "Meta", url: "https://169.254.169.254/catalog.json" },
+ { id: "plain", name: "Plain", url: "http://10.0.0.7:8080/catalog.json" },
+ ]),
+ ),
+ ).toEqual(["lan"]);
+ expect(
+ ids(
+ sanitizeSkillSources(
+ [
+ { id: "lan", name: "LAN", url: "https://192.168.1.5:8443/catalog.json" },
+ { id: "plain", name: "Plain", url: "http://10.0.0.7:8080/catalog.json" },
+ ],
+ { allowInsecureHttp: true },
+ ),
+ ),
+ ).toEqual(["lan", "plain"]);
+ });
+});
diff --git a/packages/shared/src/skill-catalog.ts b/packages/shared/src/skill-catalog.ts
index bde49b424..ecd9a8658 100644
--- a/packages/shared/src/skill-catalog.ts
+++ b/packages/shared/src/skill-catalog.ts
@@ -9,7 +9,7 @@
* picks share these rules.
*/
import type { UserSkillInput } from "./types.js";
-import { isSafePublicHttpsUrl } from "./public-network.js";
+import { isSafeUserEndpointUrl } from "./public-network.js";
export type SkillCatalogCategory = "workflow" | "writing" | "coding" | "data" | "docs";
@@ -40,8 +40,20 @@ export const MAX_SKILL_DOCUMENT_BYTES = 128 * 1024;
/** Host `valid_capability_id`: lowercase ASCII, digits, hyphen; starts alphanumeric. */
const SKILL_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
-export function isSafeSkillSourceUrl(url: string): boolean {
- return isSafePublicHttpsUrl(url);
+/**
+ * Guard for a skill market source URL the user entered.
+ *
+ * The user typed this address, so it may be a LAN or loopback catalog under the
+ * stored `networkPolicy`; plain `http` needs the explicit opt-in. A document URL
+ * that arrives inside a catalog stays on the third-party policy, so loosening
+ * this guard never widens the boundary for content the app did not receive from
+ * the user.
+ */
+export function isSafeSkillSourceUrl(
+ url: string,
+ options: { allowInsecureHttp?: boolean } = {},
+): boolean {
+ return isSafeUserEndpointUrl(url, options);
}
/**
@@ -177,7 +189,10 @@ export function mergeSkillEntries(
}
/** Repair whatever the renderer persisted into a usable source list. */
-export function sanitizeSkillSources(value: unknown): SkillMarketSource[] {
+export function sanitizeSkillSources(
+ value: unknown,
+ options: { allowInsecureHttp?: boolean } = {},
+): SkillMarketSource[] {
const raw = Array.isArray(value) ? value : [];
const seen = new Set<string>();
const sources: SkillMarketSource[] = [];
@@ -188,7 +203,7 @@ export function sanitizeSkillSources(value: unknown): SkillMarketSource[] {
typeof candidate.id !== "string" ||
typeof candidate.name !== "string" ||
typeof candidate.url !== "string" ||
- !isSafeSkillSourceUrl(candidate.url) ||
+ !isSafeSkillSourceUrl(candidate.url, options) ||
seen.has(candidate.id)
) {
continue;
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index 538e77050..aa9400afb 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -2,6 +2,7 @@
import type { CommandShellId } from "../command-shells.js";
import type { KeybindingOverrides } from "../keyboard-shortcuts.js";
import type { NetworkProxySettings } from "../network-proxy.js";
+import type { NetworkPolicySettings } from "../network-policy.js";
import type { ContextCompactionSettings } from "./sessions.js";
import type { Mode } from "./common.js";
import type { GlobalPermissionMode } from "./permissions.js";
@@ -117,6 +118,12 @@ export type AppSettings = {
* is set. See `network-proxy.ts`.
*/
networkProxy?: NetworkProxySettings;
+ /**
+ * Trust policy for the network endpoints the user enters themselves: how a
+ * user-supplied model base URL, MCP server, or market source is judged.
+ * Absent means the defaults in `network-policy.ts`.
+ */
+ networkPolicy?: NetworkPolicySettings;
/**
* Preferred destination when clicking HTTP/HTTPS links in chat messages.
* `workpanel`: Preview in the Work Panel browser tab (default).
diff --git a/scripts/e2e-mcp-market.mjs b/scripts/e2e-mcp-market.mjs
index fd730b8d9..856be223a 100644
--- a/scripts/e2e-mcp-market.mjs
+++ b/scripts/e2e-mcp-market.mjs
@@ -9,8 +9,10 @@
* E2E-MCP-MARKET-HEADER-SCOPE header credential stays out of the URL
* through mapping, resolution and persistence; unbound
* headers stay literal with a partial binding map
- * E2E-MCP-MARKET-NET-BOUNDARY the URL guard rejects loopback/private/
- * mapped/ULA/link-local bypass forms
+ * E2E-MCP-MARKET-NET-BOUNDARY a user source may be loopback/private (and
+ * plaintext under the stored opt-in), while a
+ * registry remote, a catalog body endpoint and
+ * any cloud metadata host stay public-only
*
* Env: PI_DESKTOP_HOST_BIN (optional), DEBUG_HOST for tracing.
* Deterministic: no live network access.
@@ -26,6 +28,7 @@ import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";
import {
BUILTIN_MCP_CATALOG,
GLOBAL_SCOPE,
+ isPublicHttpsUrl,
isPublicIpLiteral,
isSafeMarketSourceUrl,
mapRegistryServer,
@@ -113,33 +116,98 @@ class Host {
// ── E2E-MCP-MARKET-NET-BOUNDARY ──────────────────────────────────────────
{
- const bypass = [
+ // A market source URL is an address the user typed into a settings field, so
+ // their own machine and their own LAN are reachable there, and a plaintext
+ // source is reachable once the stored `networkPolicy` accepts it. Everything
+ // the source *returns* — a registry record, a catalog body, a redirect target
+ // — keeps the public-only rule, because that is the input an attacker holds.
+ const userAccepted = [
+ "https://127.0.0.1/x",
+ "https://10.1.2.3/x",
+ "https://192.168.1.5:8443/x",
"https://localhost./x",
+ "https://nas.local/x",
"https://[::1]/x",
"https://[::ffff:127.0.0.1]/x",
"https://[fd00::1]/x",
"https://[fe80::1]/x",
"https://[fec0::1]/x",
- "https://127.0.0.1/x",
- "https://10.1.2.3/x",
- "https://192.0.0.1/x",
- "https://198.18.0.1/x",
+ ];
+ const userRefused = [
+ "https://169.254.169.254/x",
+ "https://169.254.169.254./x",
+ "https://100.100.100.200/x",
+ "https://[fd00:ec2::254]/x",
+ "https://metadata.google.internal/x",
+ "https://metadata./x",
+ "https://instance-data/x",
+ "https://0.0.0.0/x",
+ "https://[::]/x",
+ "https://239.1.2.3/x",
"https://240.0.0.1/x",
- "https://192.168.1.1/x",
- "https://[2001:2::1]/x",
+ "https://192.0.2.1/x",
+ "https://[2001:db8::1]/x",
"https://user:[email protected]/x",
+ "file:///etc/passwd",
+ "not a url",
+ ];
+ const userPlaintext = [
+ "http://registry.example/x",
+ "http://10.0.0.7:8080/x",
+ "http://nas.local/x",
+ ];
+ const userGateOk =
+ userAccepted.every((url) => isSafeMarketSourceUrl(url) === true) &&
+ userRefused.every((url) => isSafeMarketSourceUrl(url) === false) &&
+ userPlaintext.every((url) => isSafeMarketSourceUrl(url) === false) &&
+ userPlaintext.every((url) => isSafeMarketSourceUrl(url, { allowInsecureHttp: true }) === true) &&
+ isSafeMarketSourceUrl("http://169.254.169.254/x", { allowInsecureHttp: true }) === false;
+
+ // The third-party positions: a registry record's remote URL and a catalog
+ // body's endpoint, neither of which the user typed.
+ const thirdPartyRefused = [
+ "https://127.0.0.1/x",
+ "https://10.1.2.3/x",
+ "https://192.168.1.5/x",
+ "https://[fd00::1]/x",
+ "https://[fe80::1]/x",
+ "https://169.254.169.254/x",
+ "https://nas.local/x",
"http://registry.example/x",
];
const accepted = "https://registry.modelcontextprotocol.io/v0/servers";
- const rejectedAll = bypass.every((url) => isSafeMarketSourceUrl(url) === false);
const publicOk =
isSafeMarketSourceUrl(accepted) &&
isSafeMarketSourceUrl("https://[2606:4700::1]/x") &&
- isPublicIpLiteral("2606:4700:4700::1111");
+ isPublicIpLiteral("2606:4700:4700::1111") &&
+ isPublicHttpsUrl(accepted);
+ const thirdPartyOk =
+ thirdPartyRefused.every((url) => isPublicHttpsUrl(url) === false) &&
+ mapRegistryServer({
+ server: {
+ name: "io.example/private-remote",
+ remotes: [{ type: "streamable-http", url: "https://192.168.1.5/mcp" }],
+ },
+ }) === null;
+ // A catalog body that names an internal endpoint is dropped, not installed.
+ const body = validateMcpCatalogFile({
+ schemaVersion: 1,
+ servers: [
+ { id: "body-private", name: "Body private", transport: "http", url: "https://10.0.0.8/mcp" },
+ { id: "body-public", name: "Body public", transport: "http", url: "https://mcp.example/mcp" },
+ ],
+ });
+ const bodyOk =
+ body.catalog.servers.map((server) => server.id).join(",") === "body-public" &&
+ body.warnings.some((warning) => warning.includes("public https address"));
+
+ const ok = userGateOk && publicOk && thirdPartyOk && bodyOk;
record(
"E2E-MCP-MARKET-NET-BOUNDARY",
- rejectedAll && publicOk,
- rejectedAll && publicOk ? "15 bypass forms rejected, public accepted" : "guard misclassification"
+ ok,
+ ok
+ ? `${userAccepted.length} user forms accepted (${userRefused.length} refused, ${userPlaintext.length} plaintext gated), ${thirdPartyRefused.length} third-party forms rejected`
+ : "guard misclassification"
);
}
diff --git a/scripts/e2e-skill-market.mjs b/scripts/e2e-skill-market.mjs
index 3236373f8..620cc90c4 100644
--- a/scripts/e2e-skill-market.mjs
+++ b/scripts/e2e-skill-market.mjs
@@ -6,9 +6,10 @@
* E2E-SKILL-MARKET-INSTALL builtin entry → assembled document →
* skills.create → record on disk
* E2E-SKILL-MARKET-EXPANSION adjacent resources expand into the body
- * E2E-SKILL-MARKET-NET-BOUNDARY URL guard rejects loopback/private/mapped/
- * ULA/link-local bypass forms
- * E2E-SKILL-MARKET-ID-ALIGN scanned ids match host valid_capability_id
+ * E2E-SKILL-MARKET-NET-BOUNDARY a user source may be loopback/private (and
+ * plaintext under the stored opt-in), while a
+ * document URL a catalog carries stays
+ * public-only
* E2E-SKILL-MARKET-SIZE-LIMIT expanded documents over 128KiB are flagged
*
* Env: PI_DESKTOP_HOST_BIN (optional), DEBUG_HOST for tracing.
@@ -27,6 +28,7 @@ import {
GLOBAL_SCOPE,
assembleSkillInstall,
expandSkillResources,
+ isPublicHttpsUrl,
isSafeSkillSourceUrl,
MAX_SKILL_DOCUMENT_BYTES,
sanitizeSkillCatalogId,
@@ -114,22 +116,65 @@ class Host {
// ── E2E-SKILL-MARKET-NET-BOUNDARY ────────────────────────────────────────
{
- const bypass = [
+ // A skill market source URL is an address the user typed, so a catalog on
+ // their own machine or LAN is reachable — a plaintext one once the stored
+ // `networkPolicy` accepts it. A document URL the catalog carries is content
+ // the app did not receive from the user, so that one stays public-only.
+ const userAccepted = [
"https://localhost./x/catalog.json",
+ "https://127.0.0.1/catalog.json",
+ "https://10.0.0.8/catalog.json",
+ "https://192.168.1.5:8443/catalog.json",
"https://[::1]/catalog.json",
"https://[::ffff:127.0.0.1]/catalog.json",
"https://[fd00::1]/catalog.json",
"https://[fe80::1]/catalog.json",
- "https://127.0.0.1/catalog.json",
- "https://10.0.0.8/catalog.json",
+ ];
+ const userRefused = [
+ "https://169.254.169.254/catalog.json",
+ "https://100.100.100.200/catalog.json",
+ "https://[fd00:ec2::254]/catalog.json",
+ "https://metadata.google.internal/catalog.json",
+ "https://metadata./catalog.json",
+ "https://[2001:db8::1]/catalog.json",
+ "https://user:[email protected]/catalog.json",
+ "file:///etc/passwd",
+ ];
+ const userPlaintext = [
+ "http://192.168.1.5/catalog.json",
"http://skills.example/catalog.json",
];
+ const userGateOk =
+ userAccepted.every((url) => isSafeSkillSourceUrl(url) === true) &&
+ userRefused.every((url) => isSafeSkillSourceUrl(url) === false) &&
+ userPlaintext.every((url) => isSafeSkillSourceUrl(url) === false) &&
+ userPlaintext.every((url) => isSafeSkillSourceUrl(url, { allowInsecureHttp: true }) === true) &&
+ isSafeSkillSourceUrl("http://169.254.169.254/catalog.json", { allowInsecureHttp: true }) ===
+ false;
+
+ // Document URLs are third-party content: a catalog the user added still may
+ // not aim the app at their own network, and the main-process scan refuses
+ // these before any fetch (`skill-market-scan.ts`, `fetchEntryDocument`).
+ const documentRefused = [
+ "https://127.0.0.1/SKILL.md",
+ "https://10.0.0.8/SKILL.md",
+ "https://192.168.1.5/SKILL.md",
+ "https://[fd00::1]/SKILL.md",
+ "https://169.254.169.254/SKILL.md",
+ "https://nas.local/SKILL.md",
+ "http://cdn.jsdelivr.net/gh/anthropics/skills@main/SKILL.md",
+ ];
const accepted = "https://cdn.jsdelivr.net/gh/anthropics/skills@main/skills/pdf/SKILL.md";
- const rejectedAll = bypass.every((url) => isSafeSkillSourceUrl(url) === false);
+ const thirdPartyOk =
+ documentRefused.every((url) => isPublicHttpsUrl(url) === false) && isPublicHttpsUrl(accepted);
+
+ const ok = userGateOk && thirdPartyOk && isSafeSkillSourceUrl(accepted);
record(
"E2E-SKILL-MARKET-NET-BOUNDARY",
- rejectedAll && isSafeSkillSourceUrl(accepted),
- rejectedAll ? "8 bypass forms rejected, public CDN accepted" : "guard misclassification",
+ ok,
+ ok
+ ? `${userAccepted.length} user forms accepted (${userRefused.length} refused, ${userPlaintext.length} plaintext gated), ${documentRefused.length} third-party document forms rejected`
+ : "guard misclassification",
);
}