diff --git a/docs/plugins.md b/docs/plugins.md index 36b8c4143b..248a758943 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -103,6 +103,12 @@ The `worktree-include` built-in copies gitignored files selected by [`.worktreeinclude`](../public-docs/worktrees.md#copy-local-files-with-worktreeinclude) before setup and agents, through `worktree.create.after`. +The `cloudflared-tunnel` and `tailscale-funnel` built-ins register tunnel providers through +`server.registerTunnelProvider()`. Both start without installed binaries or credentials and report +availability through `status()`. Quick mode in `cloudflared-tunnel` forwards the local HTTP target +directly with `--url`, while named mode passes `TUNNEL_TOKEN` via environment and runs the +remotely configured Cloudflare tunnel (`cloudflared tunnel --no-autoupdate run`). + Desktop packaging ships the entire built-in plugin directory as an external resource, including declarations. The external esbuild compiler cannot read Electron's `app.asar` filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation. diff --git a/packages/plugin/src/boundaries.test.ts b/packages/plugin/src/boundaries.test.ts index 5374e80bac..3a3d19d721 100644 --- a/packages/plugin/src/boundaries.test.ts +++ b/packages/plugin/src/boundaries.test.ts @@ -779,3 +779,76 @@ describe("plugin notifications SDK boundary", () => { ).toEqual([]); }); }); + +describe("tunnel provider SDK boundary", () => { + it("types tunnel provider registration, status union, lifecycle events, and cleanup", () => { + expect( + typeErrors(` + import type { + PluginServerContext, + TunnelEvent, + TunnelOpenContext, + TunnelProviderRegistration, + TunnelProviderStatus, + TunnelStability, + TunnelStatusContext, + TunnelTarget, + } from "@getpaseo/plugin/server"; + + export default function contribute(server: PluginServerContext) { + const provider: TunnelProviderRegistration = { + id: "acme-tunnel", + label: "Acme Tunnel", + description: "Expose local HTTP targets through Acme.", + docsUrl: "https://example.com/docs/tunnel", + async status({ paseo, signal }: TunnelStatusContext): Promise { + void paseo; + if (signal.aborted) { + return { + status: "unavailable", + reason: "Probe aborted", + installUrl: "https://example.com/install", + fixHint: "Retry the probe.", + }; + } + return { status: "available", detail: "v1.0.0" }; + }, + async open(target: TunnelTarget, { paseo, signal, report }: TunnelOpenContext) { + const id: string = target.id; + const host: string = target.host; + const port: number = target.port; + const label: string | undefined = target.label; + const slug: string | undefined = target.slug; + void [id, host, port, label, slug, paseo]; + // @ts-expect-error target fields are read-only + target.port = 8080; + const stability: TunnelStability = "ephemeral"; + const connecting: TunnelEvent = { type: "connecting" }; + const ready: TunnelEvent = { + type: "ready", + url: "https://demo.example.com", + stability, + }; + const reconnecting: TunnelEvent = { type: "reconnecting", reason: "network changed" }; + const error: TunnelEvent = { type: "error", message: "dropped", recoverable: true }; + const closed: TunnelEvent = { type: "closed", reason: "aborted" }; + report(connecting); + report(ready); + report(reconnecting); + report(error); + report(closed); + // @ts-expect-error ready event requires a url + report({ type: "ready" }); + // @ts-expect-error status requires a valid discriminant + const badStatus: TunnelProviderStatus = { available: true }; + void badStatus; + void signal; + }, + }; + const dispose: () => void = server.registerTunnelProvider(provider); + return dispose; + } + `), + ).toEqual([]); + }); +}); diff --git a/packages/plugin/src/server/contracts.ts b/packages/plugin/src/server/contracts.ts index e252cd5108..6dd23170a3 100644 --- a/packages/plugin/src/server/contracts.ts +++ b/packages/plugin/src/server/contracts.ts @@ -6,6 +6,7 @@ import type { ProviderRegistration } from "./provider.js"; import type { UsageSourceRegistration } from "./usage.js"; import type { PluginLifecycleRegistration } from "./lifecycle.js"; import type { PluginNotifications } from "./notifications.js"; +import type { TunnelProviderRegistration } from "./tunnel.js"; import type { WorktreeManagerRegistration } from "./worktree.js"; export interface PluginHandlerContext { @@ -67,6 +68,7 @@ export interface PluginServerContext extends PluginLifecycleRegistration { registerProvider(provider: ProviderRegistration): void; registerUsageSource(source: UsageSourceRegistration): void; registerWorktreeManager(manager: WorktreeManagerRegistration): () => void; + registerTunnelProvider(provider: TunnelProviderRegistration): () => void; notifications: PluginNotifications; } diff --git a/packages/plugin/src/server/index.ts b/packages/plugin/src/server/index.ts index 5179c79d37..1882b38fc8 100644 --- a/packages/plugin/src/server/index.ts +++ b/packages/plugin/src/server/index.ts @@ -45,6 +45,15 @@ export type { PluginNotificationSendResult, PluginNotificationOpenTarget, } from "./notifications.js"; +export type { + TunnelEvent, + TunnelOpenContext, + TunnelProviderRegistration, + TunnelProviderStatus, + TunnelStability, + TunnelStatusContext, + TunnelTarget, +} from "./tunnel.js"; export type { PluginWorktreeContext, PluginWorktreeCreateInput, diff --git a/packages/plugin/src/server/tunnel.ts b/packages/plugin/src/server/tunnel.ts new file mode 100644 index 0000000000..028854d8c8 --- /dev/null +++ b/packages/plugin/src/server/tunnel.ts @@ -0,0 +1,50 @@ +import type { PaseoApi } from "@getpaseo/client"; + +export type TunnelStability = "ephemeral" | "stable"; + +export interface TunnelTarget { + readonly id: string; + readonly host: string; + readonly port: number; + readonly label?: string; + readonly slug?: string; +} + +export type TunnelProviderStatus = + | { + status: "available"; + detail?: string; + } + | { + status: "unavailable"; + reason: string; + installUrl?: string; + fixHint?: string; + }; + +export type TunnelEvent = + | { type: "connecting"; detail?: string } + | { type: "ready"; url: string; stability?: TunnelStability; detail?: string } + | { type: "reconnecting"; reason?: string } + | { type: "error"; message: string; recoverable?: boolean } + | { type: "closed"; reason?: string }; + +export interface TunnelStatusContext { + readonly paseo: PaseoApi; + readonly signal: AbortSignal; +} + +export interface TunnelOpenContext { + readonly paseo: PaseoApi; + readonly signal: AbortSignal; + report(event: TunnelEvent): void; +} + +export interface TunnelProviderRegistration { + readonly id: string; + readonly label: string; + readonly description?: string; + readonly docsUrl?: string; + status(context: TunnelStatusContext): Promise; + open(target: TunnelTarget, context: TunnelOpenContext): Promise; +} diff --git a/packages/protocol/src/messages.ts b/packages/protocol/src/messages.ts index 30fa22ec91..8262b7b242 100644 --- a/packages/protocol/src/messages.ts +++ b/packages/protocol/src/messages.ts @@ -19,6 +19,18 @@ import { HostsRouteFrameSchema, HostsRouteClosedSchema, } from "./hosts.js"; +import { + TunnelProvidersListRequestSchema, + TunnelProvidersListResponseSchema, + TunnelExposuresListRequestSchema, + TunnelExposuresListResponseSchema, + TunnelExposureChangedSchema, + TunnelExposureOpenRequestSchema, + TunnelExposureOpenResponseSchema, + TunnelExposureCloseRequestSchema, + TunnelExposureCloseResponseSchema, +} from "./tunnels.js"; +export * from "./tunnels.js"; import { PluginRegistryIdSchema, PluginRegistryIdentitySchema, @@ -3607,6 +3619,10 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [ HostsRouteOpenRequestSchema, HostsRouteFrameRequestSchema, HostsRouteCloseRequestSchema, + TunnelProvidersListRequestSchema, + TunnelExposuresListRequestSchema, + TunnelExposureOpenRequestSchema, + TunnelExposureCloseRequestSchema, NetworkTunnelCreateTicketRequestSchema, BrowserHostRegisterRequestSchema, @@ -4110,6 +4126,8 @@ export const ServerInfoStatusPayloadSchema = z pluginSubscriptions: z.boolean().optional(), // COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01. pluginNotifications: z.boolean().optional(), + // COMPAT(tunnelProviders): added in v0.18.0, remove gate after 2027-06-01. + tunnelProviders: z.boolean().optional(), // COMPAT(skillManagement): added in v0.4.0, remove gate after 2027-08-16. skillManagement: z.boolean().optional(), // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26. @@ -7799,6 +7817,11 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [ HostsRouteOpenResponseSchema, HostsRouteFrameSchema, HostsRouteClosedSchema, + TunnelProvidersListResponseSchema, + TunnelExposuresListResponseSchema, + TunnelExposureChangedSchema, + TunnelExposureOpenResponseSchema, + TunnelExposureCloseResponseSchema, NetworkTunnelCreateTicketResponseSchema, BrowserHostRegisterResponseSchema, diff --git a/packages/protocol/src/tunnels.test.ts b/packages/protocol/src/tunnels.test.ts new file mode 100644 index 0000000000..873ccc929f --- /dev/null +++ b/packages/protocol/src/tunnels.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from "vitest"; +import { + ServerInfoStatusPayloadSchema, + SessionInboundMessageSchema, + SessionOutboundMessageSchema, +} from "./messages.js"; + +describe("tunnel protocol schemas", () => { + it("accepts tunnel inbound requests and outbound responses/events", () => { + const providerListReq = SessionInboundMessageSchema.parse({ + type: "tunnel.providers.list.request", + requestId: "req-1", + }); + expect(providerListReq.type).toBe("tunnel.providers.list.request"); + + const openReq = SessionInboundMessageSchema.parse({ + type: "tunnel.exposure.open.request", + requestId: "req-2", + providerId: "cloudflared", + host: "127.0.0.1", + port: 4321, + label: "External MCP", + slug: "mcp", + }); + expect(openReq.type).toBe("tunnel.exposure.open.request"); + + const closeReq = SessionInboundMessageSchema.parse({ + type: "tunnel.exposure.close.request", + requestId: "req-3", + exposureId: "tun_1", + }); + expect(closeReq.type).toBe("tunnel.exposure.close.request"); + + const exposure = { + id: "tun_1", + providerId: "cloudflared", + target: { host: "127.0.0.1", port: 4321, label: "External MCP", slug: "mcp" }, + state: "ready" as const, + url: "https://demo.trycloudflare.com", + stability: "ephemeral" as const, + detail: null, + error: null, + createdAt: "2026-11-27T10:00:00.000Z", + updatedAt: "2026-11-27T10:00:01.000Z", + }; + + const listRes = SessionOutboundMessageSchema.parse({ + type: "tunnel.exposures.list.response", + payload: { + requestId: "req-4", + exposures: [exposure], + subscriptionId: "sub-1", + }, + }); + expect(listRes.type).toBe("tunnel.exposures.list.response"); + + const changed = SessionOutboundMessageSchema.parse({ + type: "tunnel.exposure.changed", + payload: { + subscriptionId: "sub-1", + exposure, + }, + }); + expect(changed.type).toBe("tunnel.exposure.changed"); + + const providersRes = SessionOutboundMessageSchema.parse({ + type: "tunnel.providers.list.response", + payload: { + requestId: "req-1", + providers: [ + { + id: "cloudflared", + pluginId: "cloudflared-tunnel", + label: "Cloudflare Tunnel", + availability: { status: "available", detail: "cloudflared 2026.1.0" }, + }, + { + id: "tailscale-funnel", + pluginId: "tailscale-funnel", + label: "Tailscale Funnel", + availability: { + status: "unavailable", + reason: "tailscale CLI is not installed", + installUrl: "https://tailscale.com/download", + }, + }, + ], + }, + }); + expect(providersRes.type).toBe("tunnel.providers.list.response"); + }); + + it("exposes optional server_info.features.tunnelProviders while remaining backward compatible", () => { + const base = { + status: "server_info" as const, + serverId: "srv_1", + hostname: "devbox", + version: "0.17.6", + }; + expect( + ServerInfoStatusPayloadSchema.parse({ ...base, features: { tunnelProviders: true } }).features + ?.tunnelProviders, + ).toBe(true); + expect( + ServerInfoStatusPayloadSchema.parse({ ...base, features: {} }).features?.tunnelProviders, + ).toBeUndefined(); + }); +}); diff --git a/packages/protocol/src/tunnels.ts b/packages/protocol/src/tunnels.ts new file mode 100644 index 0000000000..a64f42ac5d --- /dev/null +++ b/packages/protocol/src/tunnels.ts @@ -0,0 +1,130 @@ +import { z } from "zod"; + +export const TunnelStabilitySchema = z.enum(["ephemeral", "stable"]); + +export const TunnelExposureStateSchema = z.enum([ + "connecting", + "ready", + "reconnecting", + "error", + "closed", +]); + +export const TunnelProviderAvailabilitySchema = z.discriminatedUnion("status", [ + z.object({ + status: z.literal("available"), + detail: z.string().optional(), + }), + z.object({ + status: z.literal("unavailable"), + reason: z.string(), + installUrl: z.string().optional(), + fixHint: z.string().optional(), + }), +]); + +export const TunnelProviderInfoSchema = z.object({ + id: z.string(), + pluginId: z.string(), + label: z.string(), + description: z.string().optional(), + docsUrl: z.string().optional(), + availability: TunnelProviderAvailabilitySchema, +}); + +export const TunnelExposureTargetSchema = z.object({ + host: z.string(), + port: z.number().int().min(1).max(65535), + label: z.string().optional(), + slug: z.string().optional(), +}); + +export const TunnelExposureSchema = z.object({ + id: z.string(), + providerId: z.string(), + target: TunnelExposureTargetSchema, + state: TunnelExposureStateSchema, + url: z.string().nullable(), + stability: TunnelStabilitySchema.nullable(), + detail: z.string().nullable(), + error: z.string().nullable(), + createdAt: z.string(), + updatedAt: z.string(), +}); + +export type TunnelStabilityWire = z.infer; +export type TunnelExposureState = z.infer; +export type TunnelProviderAvailability = z.infer; +export type TunnelProviderInfo = z.infer; +export type TunnelExposureTarget = z.infer; +export type TunnelExposure = z.infer; + +export const TunnelProvidersListRequestSchema = z.object({ + type: z.literal("tunnel.providers.list.request"), + requestId: z.string(), +}); + +export const TunnelProvidersListResponseSchema = z.object({ + type: z.literal("tunnel.providers.list.response"), + payload: z.object({ + requestId: z.string(), + providers: z.array(TunnelProviderInfoSchema), + }), +}); + +export const TunnelExposuresListRequestSchema = z.object({ + type: z.literal("tunnel.exposures.list.request"), + requestId: z.string(), + observe: z.boolean().optional(), +}); + +export const TunnelExposuresListResponseSchema = z.object({ + type: z.literal("tunnel.exposures.list.response"), + payload: z.object({ + requestId: z.string(), + exposures: z.array(TunnelExposureSchema), + subscriptionId: z.string().optional(), + }), +}); + +export const TunnelExposureChangedSchema = z.object({ + type: z.literal("tunnel.exposure.changed"), + payload: z.object({ + subscriptionId: z.string(), + exposure: TunnelExposureSchema, + }), +}); + +export const TunnelExposureOpenRequestSchema = z.object({ + type: z.literal("tunnel.exposure.open.request"), + requestId: z.string(), + providerId: z.string().min(1).max(256), + host: z.string().min(1).max(256), + port: z.number().int().min(1).max(65535), + id: z.string().min(1).max(256).optional(), + label: z.string().max(256).optional(), + slug: z.string().max(256).optional(), +}); + +export const TunnelExposureOpenResponseSchema = z.object({ + type: z.literal("tunnel.exposure.open.response"), + payload: z.object({ + requestId: z.string(), + exposure: TunnelExposureSchema, + }), +}); + +export const TunnelExposureCloseRequestSchema = z.object({ + type: z.literal("tunnel.exposure.close.request"), + requestId: z.string(), + exposureId: z.string().min(1).max(256), +}); + +export const TunnelExposureCloseResponseSchema = z.object({ + type: z.literal("tunnel.exposure.close.response"), + payload: z.object({ + requestId: z.string(), + exposureId: z.string(), + closed: z.boolean(), + }), +}); diff --git a/packages/server/src/server/authorization/operation-permissions.ts b/packages/server/src/server/authorization/operation-permissions.ts index 8fcdce59b2..fafc6e877d 100644 --- a/packages/server/src/server/authorization/operation-permissions.ts +++ b/packages/server/src/server/authorization/operation-permissions.ts @@ -10,6 +10,10 @@ const INBOUND_PERMISSION = { "hosts.add.request": "tunnel.manage", "hosts.update.request": "tunnel.manage", "hosts.remove.request": "tunnel.manage", + "tunnel.providers.list.request": ["daemon.read", "tunnel.manage"], + "tunnel.exposures.list.request": ["daemon.read", "tunnel.manage"], + "tunnel.exposure.open.request": "tunnel.manage", + "tunnel.exposure.close.request": "tunnel.manage", "hosts.link.open.request": null, "hosts.link.ack.request": null, "hosts.route.open.request": null, @@ -254,6 +258,11 @@ const OUTBOUND_PERMISSION = { "hosts.add.response": "tunnel.manage", "hosts.update.response": "tunnel.manage", "hosts.remove.response": "tunnel.manage", + "tunnel.providers.list.response": ["daemon.read", "tunnel.manage"], + "tunnel.exposures.list.response": ["daemon.read", "tunnel.manage"], + "tunnel.exposure.changed": ["daemon.read", "tunnel.manage"], + "tunnel.exposure.open.response": "tunnel.manage", + "tunnel.exposure.close.response": "tunnel.manage", "hosts.link.open.response": null, "hosts.route.open.response": null, "hosts.route.frame": null, diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 00b27544b2..de10f7a76f 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -215,6 +215,7 @@ import { } from "./hub/relationship-remote.js"; import { DaemonExecutions } from "./hub/daemon-executions.js"; import { PluginService } from "./plugins/index.js"; +import { TunnelManager } from "./tunnels/index.js"; import { BuiltinPluginLoader } from "./plugins/builtin/index.js"; import { ManagedPluginSources } from "./plugins/managed-source.js"; @@ -460,6 +461,7 @@ export interface PaseoDaemon { agentStorage: AgentStorage; terminalManager: TerminalManager; serviceProxy: ServiceProxySubsystem; + tunnelManager: TunnelManager; scriptRuntimeStore: WorkspaceScriptRuntimeStore; browserToolsBroker: BrowserToolsBroker; start(): Promise; @@ -646,7 +648,9 @@ export async function createPaseoDaemon( }); const browserToolsPolicy = new DaemonConfigBrowserToolsPolicy(daemonConfigStore); const browserToolsBroker = new BrowserToolsBroker({}); + const tunnelManager = new TunnelManager({ logger }); const pluginRuntime: PluginService = new PluginService(logger, daemonConfigStore, daemonVersion, { + tunnelManager, usageAgents: { hasAgent: (id) => agentManager.getAgent(id) !== null, usageSession: (id) => agentManager.usageSession(id), @@ -1955,6 +1959,7 @@ export async function createPaseoDaemon( workspaceLabelService, workspaceArchiveOperations, config.pushNotifications, + tunnelManager, ); pluginRuntime.bindPaseoSessionHost(wsServer); await pluginRuntime.start(); @@ -2023,6 +2028,7 @@ export async function createPaseoDaemon( localCredential = null; await deleteLocalCredential(config.paseoHome); unsubscribePluginProviders(); + await tunnelManager.closeAll().catch(() => undefined); await pluginRuntime.stopAllPlugins().catch(() => undefined); await serviceProxy.stopStandalone().catch(() => undefined); await agentProviderRuntime.shutdown().catch(() => undefined); @@ -2085,6 +2091,11 @@ export async function createPaseoDaemon( ); await agentStorage.flush().catch(() => undefined); } + await withTimeout({ + promise: tunnelManager.closeAll(), + timeoutMs: AGENT_CLOSE_TIMEOUT_MS, + label: "close active tunnels", + }).catch((error) => logger.warn({ err: error }, "Failed to close active tunnels")); await pluginRuntime.stopAllPlugins(); try { if (keepTerminals) { @@ -2134,6 +2145,7 @@ export async function createPaseoDaemon( agentStorage, terminalManager, serviceProxy, + tunnelManager, scriptRuntimeStore, browserToolsBroker, start, diff --git a/packages/server/src/server/plugins/builtin/index.ts b/packages/server/src/server/plugins/builtin/index.ts index 8abf03805b..f296573615 100644 --- a/packages/server/src/server/plugins/builtin/index.ts +++ b/packages/server/src/server/plugins/builtin/index.ts @@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url"; export const builtinPlugins = [ "antigravity-provider", "claude-usage-source", + "cloudflared-tunnel", "codex-usage-source", "copilot-usage-source", "cursor-usage-source", @@ -18,6 +19,7 @@ export const builtinPlugins = [ "muse-provider", "opencode-go-usage-source", "openrouter-host-usage-source", + "tailscale-funnel", "worktree-include", "zai-usage-source", ] as const; diff --git a/packages/server/src/server/plugins/index.ts b/packages/server/src/server/plugins/index.ts index 8cd7305c74..a954bc7679 100644 --- a/packages/server/src/server/plugins/index.ts +++ b/packages/server/src/server/plugins/index.ts @@ -30,14 +30,16 @@ import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js"; import type { PluginProviderInstallationMetadata, PluginProviderMetadata, + PluginTunnelProviderMetadata, + PluginUsageSourceMetadata, } from "./plugin-process-protocol.js"; +import type { RegisteredTunnelProvider, TunnelManager } from "../tunnels/index.js"; import { readPluginProviderIcon } from "./provider-icon.js"; import { type AgentUsageLookup, type ListUsageReportsOptions, UsageSourceRegistry, } from "./usage-sources/index.js"; -import type { PluginUsageSourceMetadata } from "./plugin-process-protocol.js"; const BUILTIN_PROVIDER_ID_SET: ReadonlySet = new Set(BUILTIN_PROVIDER_IDS); @@ -60,6 +62,9 @@ interface PluginRuntimePort { clearLogs(pluginId: string): void; getProviderRegistrations?(pluginId: string): readonly PluginProviderMetadata[]; getUsageSourceRegistrations(pluginId: string): readonly PluginUsageSourceMetadata[]; + getTunnelProviderRegistrations?(pluginId: string): readonly PluginTunnelProviderMetadata[]; + getTunnelProviderStatus?: PluginRuntime["getTunnelProviderStatus"]; + openTunnel?: PluginRuntime["openTunnel"]; fetchUsage: PluginRuntime["fetchUsage"]; discoverUsage: PluginRuntime["discoverUsage"]; connectProvider: PluginRuntime["connectProvider"]; @@ -79,6 +84,7 @@ interface PluginRuntimePort { interface PluginServiceDependencies { usageAgents?: AgentUsageLookup; + tunnelManager?: TunnelManager; settingsDirectory?: string; runtime?: PluginRuntimePort; managedSources?: ManagedPluginSources; @@ -110,6 +116,8 @@ export class PluginService { private readonly providers = new Map(); private readonly usageSources: UsageSourceRegistry; private readonly usageSourceIdsByPlugin = new Map(); + private readonly tunnelManager: TunnelManager | null; + private readonly tunnelProviderIdsByPlugin = new Map(); private readonly providerIdsByPlugin = new Map(); private readonly providerListeners = new Set<() => void>(); private lifecycle = Promise.resolve(); @@ -134,6 +142,7 @@ export class PluginService { this.logger, dependencies.usageAgents, ); + this.tunnelManager = dependencies.tunnelManager ?? null; this.runtime = dependencies.runtime ?? new PluginRuntime(logger, daemonVersion, { @@ -141,6 +150,14 @@ export class PluginService { onSettingsChanged: (pluginId, settingsId) => { for (const listener of this.settingsListeners) listener(pluginId, settingsId); }, + onTunnelProvidersChanged: (pluginId) => { + void this.syncTunnelProviders(pluginId).catch((error) => { + this.logger.warn( + { err: error, pluginId }, + "Failed to synchronize plugin tunnel providers", + ); + }); + }, }); this.managedSources = dependencies.managedSources ?? null; this.builtinPlugins = dependencies.builtinPlugins ?? new BuiltinPluginLoader(undefined, []); @@ -148,6 +165,7 @@ export class PluginService { this.runtime.subscribe((pluginId, error) => { this.removeProviderRegistrations(pluginId); this.removeUsageSources(pluginId); + void this.removeTunnelProviders(pluginId); if (error) this.errors.set(pluginId, error); this.notify(pluginId); }); @@ -277,6 +295,7 @@ export class PluginService { await this.runtime.startBuiltinPlugin?.(plugin); await this.publishProviderRegistrations(plugin.id, plugin.directory); this.publishUsageSources(plugin.id); + this.publishTunnelProviders(plugin.id); } catch (error) { this.logger.error({ err: error, pluginId: plugin.id }, "Failed to start built-in plugin"); } @@ -678,10 +697,12 @@ export class PluginService { try { await this.publishProviderRegistrations(pluginId, sourcePath); this.publishUsageSources(pluginId); + this.publishTunnelProviders(pluginId); } catch (error) { try { this.removeProviderRegistrations(pluginId); this.removeUsageSources(pluginId); + await this.removeTunnelProviders(pluginId); } finally { await this.runtime.stopPluginById(pluginId); } @@ -689,9 +710,10 @@ export class PluginService { } } - private stopPlugin(pluginId: string): Promise { + private async stopPlugin(pluginId: string): Promise { this.removeProviderRegistrations(pluginId); this.removeUsageSources(pluginId); + await this.removeTunnelProviders(pluginId); return this.runtime.stopPluginById(pluginId); } @@ -707,9 +729,80 @@ export class PluginService { this.removeProviderRegistrations(pluginId); } for (const pluginId of this.usageSourceIdsByPlugin.keys()) this.removeUsageSources(pluginId); + await Promise.all( + [...this.tunnelProviderIdsByPlugin.keys()].map((pluginId) => + this.removeTunnelProviders(pluginId), + ), + ); await this.runtime.stopAll(); } + private buildTunnelProviders(pluginId: string): RegisteredTunnelProvider[] { + const metadata = this.runtime.getTunnelProviderRegistrations?.(pluginId) ?? []; + return metadata.map((provider) => { + const entry: RegisteredTunnelProvider = { + id: provider.id, + pluginId, + label: provider.label, + description: provider.description, + docsUrl: provider.docsUrl, + status: (options) => { + if (!this.runtime.getTunnelProviderStatus) { + throw new Error("Plugin runtime cannot query tunnel provider status"); + } + return this.runtime.getTunnelProviderStatus(pluginId, provider.id, options); + }, + open: (exposureId, target, callbacks) => { + if (!this.runtime.openTunnel) { + throw new Error("Plugin runtime cannot open tunnels"); + } + return this.runtime.openTunnel(pluginId, provider.id, exposureId, target, callbacks); + }, + }; + return entry; + }); + } + + private publishTunnelProviders(pluginId: string): void { + if (!this.tunnelManager) return; + const providers = this.buildTunnelProviders(pluginId); + const registered: string[] = []; + try { + for (const provider of providers) { + this.tunnelManager.registerProvider(provider); + registered.push(provider.id); + } + } catch (error) { + for (const id of registered) { + void this.tunnelManager.unregisterProvider(id); + } + throw error; + } + if (registered.length > 0) { + this.tunnelProviderIdsByPlugin.set(pluginId, registered); + } + } + + private async syncTunnelProviders(pluginId: string): Promise { + if (!this.tunnelManager) return; + const providers = this.buildTunnelProviders(pluginId); + await this.tunnelManager.syncPluginProviders(pluginId, providers); + if (providers.length > 0) { + this.tunnelProviderIdsByPlugin.set( + pluginId, + providers.map((provider) => provider.id), + ); + } else { + this.tunnelProviderIdsByPlugin.delete(pluginId); + } + } + + private async removeTunnelProviders(pluginId: string): Promise { + this.tunnelProviderIdsByPlugin.delete(pluginId); + if (!this.tunnelManager) return; + await this.tunnelManager.unregisterPlugin(pluginId); + } + private publishUsageSources(pluginId: string): void { const metadata = this.runtime.getUsageSourceRegistrations(pluginId); const registered: string[] = []; diff --git a/packages/server/src/server/plugins/plugin-process-protocol.ts b/packages/server/src/server/plugins/plugin-process-protocol.ts index 17447b1e48..9faa72e058 100644 --- a/packages/server/src/server/plugins/plugin-process-protocol.ts +++ b/packages/server/src/server/plugins/plugin-process-protocol.ts @@ -1,5 +1,11 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types"; -import type { PluginHookAgent, PluginNotificationSendResult } from "@getpaseo/plugin/server"; +import type { + PluginHookAgent, + PluginNotificationSendResult, + TunnelEvent, + TunnelProviderStatus, + TunnelTarget, +} from "@getpaseo/plugin/server"; import { UsageScopeSchema, type UsageScope } from "@getpaseo/plugin/server/usage"; import type { ProviderCatalogOptions, @@ -57,6 +63,79 @@ export interface PluginWorktreeManagerCapabilities { hasRestore: boolean; } +export interface PluginTunnelProviderMetadata { + id: string; + label: string; + description?: string; + docsUrl?: string; +} + +export const TunnelTargetSchema: z.ZodType = z + .object({ + id: z.string().min(1), + host: z.string().min(1), + port: z.number().int().min(1).max(65535), + label: z.string().optional(), + slug: z.string().optional(), + }) + .strict(); + +export const TunnelProviderStatusSchema: z.ZodType = z.discriminatedUnion( + "status", + [ + z + .object({ + status: z.literal("available"), + detail: z.string().optional(), + }) + .strict(), + z + .object({ + status: z.literal("unavailable"), + reason: z.string().min(1), + installUrl: z.string().optional(), + fixHint: z.string().optional(), + }) + .strict(), + ], +); + +export const TunnelEventSchema: z.ZodType = z.discriminatedUnion("type", [ + z + .object({ + type: z.literal("connecting"), + detail: z.string().optional(), + }) + .strict(), + z + .object({ + type: z.literal("ready"), + url: z.string().min(1), + stability: z.enum(["ephemeral", "stable"]).optional(), + detail: z.string().optional(), + }) + .strict(), + z + .object({ + type: z.literal("reconnecting"), + reason: z.string().optional(), + }) + .strict(), + z + .object({ + type: z.literal("error"), + message: z.string().min(1), + recoverable: z.boolean().optional(), + }) + .strict(), + z + .object({ + type: z.literal("closed"), + reason: z.string().optional(), + }) + .strict(), +]); + export type PluginProcessRequest = | { type: "tool.call"; requestId: string; agent: PluginHookAgent; name: string; input: unknown } | { type: "tool.cancel"; requestId: string } @@ -100,6 +179,10 @@ export type PluginProcessRequest = | { type: "worktree.remove"; requestId: string; request: unknown } | { type: "worktree.restore"; requestId: string; request: unknown } | { type: "worktree.cancel"; requestId: string } + | { type: "tunnel.status"; requestId: string; providerId: string } + | { type: "tunnel.status.cancel"; requestId: string } + | { type: "tunnel.open"; exposureId: string; providerId: string; target: TunnelTarget } + | { type: "tunnel.close"; exposureId: string } | { type: "usage.fetch"; requestId: string; sourceId: string; input: unknown } | { type: "usage.discover"; requestId: string; sourceId: string; scope: UsageScope } | { type: "invoke"; requestId: string; method: string; input: unknown } @@ -137,6 +220,10 @@ export type PluginProcessMessage = type: "worktree_manager.changed"; worktreeManager: PluginWorktreeManagerCapabilities | null; } + | { + type: "tunnel_providers.changed"; + tunnelProviders: PluginTunnelProviderMetadata[]; + } | { type: "ready"; methods: string[]; @@ -145,7 +232,10 @@ export type PluginProcessMessage = usageSources?: PluginUsageSourceMetadata[]; hooks?: string[]; worktreeManager?: PluginWorktreeManagerCapabilities | null; + tunnelProviders?: PluginTunnelProviderMetadata[]; } + | { type: "tunnel.event"; exposureId: string; event: TunnelEvent } + | { type: "tunnel.closed"; exposureId: string; error?: string } | { type: "result"; requestId: string; output: unknown } | { type: "error"; requestId: string; error: string } | { type: "provider.installation.report"; requestId: string; report: ProviderUpdateReport } @@ -180,6 +270,15 @@ const worktreeManagerCapabilitiesSchema = z }) .strict(); +const tunnelProviderMetadataSchema = z + .object({ + id: z.string().min(1), + label: z.string().min(1), + description: z.string().optional(), + docsUrl: z.string().optional(), + }) + .strict(); + const providerMetadataSchema = z .object({ id: z.string().min(1), @@ -337,6 +436,23 @@ export const PluginProcessRequestSchema: z.ZodType = z.dis }) .strict(), z.object({ type: z.literal("worktree.cancel"), requestId: z.string().min(1) }).strict(), + z + .object({ + type: z.literal("tunnel.status"), + requestId: z.string().min(1), + providerId: z.string().min(1), + }) + .strict(), + z.object({ type: z.literal("tunnel.status.cancel"), requestId: z.string().min(1) }).strict(), + z + .object({ + type: z.literal("tunnel.open"), + exposureId: z.string().min(1), + providerId: z.string().min(1), + target: TunnelTargetSchema, + }) + .strict(), + z.object({ type: z.literal("tunnel.close"), exposureId: z.string().min(1) }).strict(), z .object({ type: z.literal("usage.fetch"), @@ -428,6 +544,12 @@ export const PluginProcessMessageSchema: z.ZodType = z.dis worktreeManager: worktreeManagerCapabilitiesSchema.nullable(), }) .strict(), + z + .object({ + type: z.literal("tunnel_providers.changed"), + tunnelProviders: z.array(tunnelProviderMetadataSchema), + }) + .strict(), z .object({ type: z.literal("ready"), @@ -437,6 +559,21 @@ export const PluginProcessMessageSchema: z.ZodType = z.dis usageSources: z.array(usageSourceMetadataSchema).optional(), hooks: hooksSchema.optional(), worktreeManager: worktreeManagerCapabilitiesSchema.nullable().optional(), + tunnelProviders: z.array(tunnelProviderMetadataSchema).optional(), + }) + .strict(), + z + .object({ + type: z.literal("tunnel.event"), + exposureId: z.string().min(1), + event: TunnelEventSchema, + }) + .strict(), + z + .object({ + type: z.literal("tunnel.closed"), + exposureId: z.string().min(1), + error: z.string().optional(), }) .strict(), z diff --git a/packages/server/src/server/plugins/plugin-process.ts b/packages/server/src/server/plugins/plugin-process.ts index dfcf8a403a..787991ca19 100644 --- a/packages/server/src/server/plugins/plugin-process.ts +++ b/packages/server/src/server/plugins/plugin-process.ts @@ -3,8 +3,11 @@ import { PluginHookHandlers } from "./lifecycle/index.js"; import { evaluateBundle } from "./bundle-evaluator.js"; import { PluginProcessRequestSchema, + TunnelEventSchema, + TunnelProviderStatusSchema, type PluginProcessMessage, type PluginProcessRequest, + type PluginTunnelProviderMetadata, } from "./plugin-process-protocol.js"; import type { UsageSourceRegistration } from "@getpaseo/plugin/server/usage"; import type { @@ -22,6 +25,7 @@ import type { PluginWorktreeCreateInput, PluginWorktreeRemoveRequest, PluginWorktreeRestoreRequest, + TunnelProviderRegistration, WorktreeManagerRegistration, } from "@getpaseo/plugin/server"; import { randomUUID } from "node:crypto"; @@ -124,8 +128,20 @@ export function createPluginWorker(options: { const subscriptions = new PluginSubscriptionHandlers({ send, sendAndWait }); const providers = new Map(); const usageSources = new Map(); + const tunnelProviders = new Map(); + const tunnelStatusRequests = new Map(); + const activeTunnels = new Map< + string, + { + providerId: string; + controller: AbortController; + abortedByHost: boolean; + done: Promise; + } + >(); let worktreeManager: WorktreeManagerRegistration | null = null; const worktreeRequests = new Map(); + let readySent = false; const providerConnections = new Map< string, { connection: ProviderConnection; unsubscribe: () => void; closing?: Promise } @@ -290,6 +306,67 @@ export function createPluginWorker(options: { }; } + function tunnelProviderCatalog(): PluginTunnelProviderMetadata[] { + return [...tunnelProviders.values()] + .sort((left, right) => left.id.localeCompare(right.id)) + .map((provider) => { + const entry: PluginTunnelProviderMetadata = { + id: provider.id, + label: provider.label, + }; + if (provider.description !== undefined) entry.description = provider.description; + if (provider.docsUrl !== undefined) entry.docsUrl = provider.docsUrl; + return entry; + }); + } + + function registerTunnelProvider(provider: TunnelProviderRegistration): () => void { + const id = typeof provider?.id === "string" ? provider.id.trim() : ""; + if (!/^[a-z][a-z0-9._-]*$/.test(id)) { + throw new Error(`Invalid tunnel provider ID: ${provider?.id}`); + } + if (typeof provider.label !== "string" || !provider.label.trim()) { + throw new Error(`Tunnel provider ${id} requires a label`); + } + if (typeof provider.status !== "function") { + throw new Error(`Tunnel provider ${id} must implement status()`); + } + if (typeof provider.open !== "function") { + throw new Error(`Tunnel provider ${id} must implement open()`); + } + if ( + provider.docsUrl !== undefined && + (typeof provider.docsUrl !== "string" || !isHttpUrl(provider.docsUrl)) + ) { + throw new Error(`Tunnel provider ${id} docsUrl must be an http(s) URL`); + } + if (tunnelProviders.has(id)) { + throw new Error(`Duplicate tunnel provider ID: ${id}`); + } + const registered: TunnelProviderRegistration = { + ...provider, + id, + label: provider.label.trim(), + }; + tunnelProviders.set(id, registered); + if (readySent && !stopping) { + send({ type: "tunnel_providers.changed", tunnelProviders: tunnelProviderCatalog() }); + } + return () => { + if (tunnelProviders.get(id) !== registered) return; + tunnelProviders.delete(id); + for (const active of activeTunnels.values()) { + if (active.providerId === id) { + active.abortedByHost = true; + active.controller.abort(new Error(`Tunnel provider unregistered: ${id}`)); + } + } + if (readySent && !stopping) { + send({ type: "tunnel_providers.changed", tunnelProviders: tunnelProviderCatalog() }); + } + }; + } + const notifications: PluginNotifications = { send(input: PluginNotificationSendInput): Promise { if (stopping) { @@ -525,6 +602,7 @@ export function createPluginWorker(options: { registerProvider, registerUsageSource, registerWorktreeManager, + registerTunnelProvider, registerSettings, notifications, addHook: hooks.addHook, @@ -554,11 +632,13 @@ export function createPluginWorker(options: { subscriptions: subscriptions.catalog(), hooks: hooks.catalog(), worktreeManager: worktreeManagerCapabilities(), + tunnelProviders: tunnelProviderCatalog(), providers: [...providers.values()] .sort((left, right) => left.id.localeCompare(right.id)) .map(providerMetadata), usageSources: usageSourceMetadata, }); + readySent = true; } async function shutdown(): Promise { @@ -574,6 +654,16 @@ export function createPluginWorker(options: { for (const request of installationRequests.values()) request.abort(new Error("Plugin is stopping")); for (const request of worktreeRequests.values()) request.abort(new Error("Plugin is stopping")); + for (const request of tunnelStatusRequests.values()) + request.abort(new Error("Plugin is stopping")); + const closingTunnels: Promise[] = []; + for (const active of activeTunnels.values()) { + active.abortedByHost = true; + active.controller.abort(new Error("Plugin is stopping")); + closingTunnels.push(active.done); + } + await Promise.allSettled(closingTunnels); + tunnelProviders.clear(); for (const pending of notificationRequests.values()) pending.reject(new Error("Plugin is stopping")); notificationRequests.clear(); @@ -622,9 +712,20 @@ export function createPluginWorker(options: { message.type === "worktree.create" || message.type === "worktree.remove" || message.type === "worktree.restore" || + message.type === "tunnel.status" || message.type === "subscribe" ) { send({ type: "error", requestId: message.requestId, error: "Plugin is stopping" }); + } else if (message.type === "tunnel.open") { + send({ + type: "tunnel.closed", + exposureId: message.exposureId, + error: "Plugin is stopping", + }); + } else if (message.type === "tunnel.close") { + if (!activeTunnels.has(message.exposureId)) { + send({ type: "tunnel.closed", exposureId: message.exposureId }); + } } else if (message.type === "provider.connect") { send({ type: "provider.connect_failed", @@ -839,6 +940,10 @@ export function createPluginWorker(options: { handleWorktreeMessage(message); return; } + if (isTunnelMessage(message)) { + handleTunnelMessage(message); + return; + } if (message.type === "invoke") invoke(message); else handleSubscriptionMessage(message); } @@ -986,6 +1091,164 @@ export function createPluginWorker(options: { ) .finally(() => worktreeRequests.delete(message.requestId)); } + + function isTunnelMessage( + message: PluginProcessRequest, + ): message is Extract< + PluginProcessRequest, + { type: "tunnel.status" | "tunnel.status.cancel" | "tunnel.open" | "tunnel.close" } + > { + return ( + message.type === "tunnel.status" || + message.type === "tunnel.status.cancel" || + message.type === "tunnel.open" || + message.type === "tunnel.close" + ); + } + + function handleTunnelMessage( + message: Extract< + PluginProcessRequest, + { type: "tunnel.status" | "tunnel.status.cancel" | "tunnel.open" | "tunnel.close" } + >, + ): void { + if (message.type === "tunnel.status.cancel") { + tunnelStatusRequests.get(message.requestId)?.abort(new Error("Tunnel status canceled")); + return; + } + if (message.type === "tunnel.close") { + const active = activeTunnels.get(message.exposureId); + if (!active) { + send({ type: "tunnel.closed", exposureId: message.exposureId }); + return; + } + active.abortedByHost = true; + active.controller.abort(new Error("Tunnel closed")); + return; + } + if (!paseo) { + if (message.type === "tunnel.status") { + send({ + type: "error", + requestId: message.requestId, + error: "Plugin Paseo API is unavailable", + }); + } else { + send({ + type: "tunnel.closed", + exposureId: message.exposureId, + error: "Plugin Paseo API is unavailable", + }); + } + return; + } + const provider = tunnelProviders.get(message.providerId); + if (!provider) { + if (message.type === "tunnel.status") { + send({ + type: "error", + requestId: message.requestId, + error: `Unknown tunnel provider: ${message.providerId}`, + }); + } else { + send({ + type: "tunnel.closed", + exposureId: message.exposureId, + error: `Unknown tunnel provider: ${message.providerId}`, + }); + } + return; + } + if (message.type === "tunnel.status") { + const controller = new AbortController(); + tunnelStatusRequests.set(message.requestId, controller); + void Promise.resolve() + .then(() => provider.status({ paseo: paseo!, signal: controller.signal })) + .then((raw) => { + const parsed = TunnelProviderStatusSchema.parse(jsonTransportValue(raw)); + if ( + parsed.status === "unavailable" && + parsed.installUrl !== undefined && + !isHttpUrl(parsed.installUrl) + ) { + throw new Error(`Tunnel provider ${provider.id} installUrl must be an http(s) URL`); + } + send({ type: "result", requestId: message.requestId, output: parsed }); + return undefined; + }) + .catch((error) => { + send({ type: "error", requestId: message.requestId, error: describeError(error) }); + return undefined; + }) + .finally(() => { + tunnelStatusRequests.delete(message.requestId); + }); + return; + } + if (activeTunnels.has(message.exposureId)) { + send({ + type: "tunnel.closed", + exposureId: message.exposureId, + error: `Duplicate tunnel exposure: ${message.exposureId}`, + }); + return; + } + const controller = new AbortController(); + let settled = false; + let reportFailure: string | undefined; + const entry = { + providerId: provider.id, + controller, + abortedByHost: false, + done: Promise.resolve(), + }; + const report = (rawEvent: unknown) => { + if (settled) return; + try { + const event = TunnelEventSchema.parse(jsonTransportValue(rawEvent)); + if (event.type === "ready" && !isHttpUrl(event.url)) { + throw new Error(`Tunnel provider ${provider.id} reported invalid URL: ${event.url}`); + } + send({ type: "tunnel.event", exposureId: message.exposureId, event }); + } catch (error) { + reportFailure = describeError(error); + controller.abort(error); + } + }; + const done = Promise.resolve() + .then(() => + provider.open(structuredClone(message.target), { + paseo: paseo!, + signal: controller.signal, + report, + }), + ) + .then( + () => { + settled = true; + activeTunnels.delete(message.exposureId); + send({ + type: "tunnel.closed", + exposureId: message.exposureId, + ...(reportFailure ? { error: reportFailure } : {}), + }); + return undefined; + }, + (error) => { + settled = true; + activeTunnels.delete(message.exposureId); + const failure = reportFailure ?? (entry.abortedByHost ? undefined : describeError(error)); + send({ + type: "tunnel.closed", + exposureId: message.exposureId, + ...(failure ? { error: failure } : {}), + }); + return undefined; + }, + ); + entry.done = done; + activeTunnels.set(message.exposureId, entry); + } return { shutdown }; } diff --git a/packages/server/src/server/plugins/runtime.ts b/packages/server/src/server/plugins/runtime.ts index 1be3470462..55c310dfc2 100644 --- a/packages/server/src/server/plugins/runtime.ts +++ b/packages/server/src/server/plugins/runtime.ts @@ -25,6 +25,9 @@ import type { PluginWorktreeCreateInput, PluginWorktreeRemoveRequest, PluginWorktreeRestoreRequest, + TunnelEvent, + TunnelProviderStatus, + TunnelTarget, } from "@getpaseo/plugin/server"; import { z } from "zod"; import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js"; @@ -49,10 +52,14 @@ import type { PluginProcessMessage, PluginProcessRequest, PluginProviderMetadata, + PluginTunnelProviderMetadata, PluginUsageSourceMetadata, PluginWorktreeManagerCapabilities, } from "./plugin-process-protocol.js"; -import { PluginProcessMessageSchema } from "./plugin-process-protocol.js"; +import { + PluginProcessMessageSchema, + TunnelProviderStatusSchema, +} from "./plugin-process-protocol.js"; import { BufferedPluginSubscription, type PluginRuntimeSubscription, @@ -148,11 +155,13 @@ interface LoadedPlugin { worktreeManager: PluginWorktreeManagerCapabilities | null; providers: readonly PluginProviderMetadata[]; usageSources: readonly PluginUsageSourceMetadata[]; + tunnelProviders: readonly PluginTunnelProviderMetadata[]; child: PluginChild | null; outputCapture: PluginOutputCapture | null; pending: Map; providerConnections: Map; providerConnectionTombstones: Set; + tunnelExposures: Map; sessionSocket: PluginSessionSocket | null; sessionClosed: Promise | null; } @@ -194,9 +203,18 @@ interface RemoteProviderConnection { rejectClosed(error: Error): void; } +interface RemoteTunnelExposure { + onEvent(event: TunnelEvent): void; + onClosed(error?: string): void; + closed: boolean; + closedPromise: Promise; + resolveClosed(): void; +} + interface PluginRuntimeDependencies { settingsDirectory?: string; onSettingsChanged?: (pluginId: string, settingsId: string) => void; + onTunnelProvidersChanged?: (pluginId: string) => void; spawnChild?: () => PluginChild; sessionHost?: PluginPaseoSessionHost; } @@ -493,6 +511,101 @@ export class PluginRuntime { return this.plugins.get(pluginId)?.usageSources ?? []; } + getTunnelProviderRegistrations(pluginId: string): readonly PluginTunnelProviderMetadata[] { + return this.plugins.get(pluginId)?.tunnelProviders ?? []; + } + + async getTunnelProviderStatus( + pluginId: string, + providerId: string, + options?: { signal?: AbortSignal }, + ): Promise { + const loaded = this.plugins.get(pluginId); + if (!loaded) throw new Error(`Plugin is not available: ${pluginId}`); + if (!loaded.tunnelProviders.some((provider) => provider.id === providerId)) { + throw new Error(`Plugin ${pluginId} does not contribute tunnel provider ${providerId}`); + } + return TunnelProviderStatusSchema.parse( + await this.request( + loaded, + { type: "tunnel.status", requestId: randomUUID(), providerId }, + { signal: options?.signal }, + ), + ); + } + + openTunnel( + pluginId: string, + providerId: string, + exposureId: string, + target: TunnelTarget, + callbacks: { + onEvent(event: TunnelEvent): void; + onClosed(error?: string): void; + }, + ): { close(): Promise } { + const loaded = this.plugins.get(pluginId); + if (!loaded?.child) throw new Error(`Plugin is not available: ${pluginId}`); + if (!loaded.tunnelProviders.some((provider) => provider.id === providerId)) { + throw new Error(`Plugin ${pluginId} does not contribute tunnel provider ${providerId}`); + } + if (loaded.tunnelExposures.has(exposureId)) { + throw new Error(`Duplicate tunnel exposure: ${exposureId}`); + } + let resolveClosed!: () => void; + const closedPromise = new Promise((resolve) => { + resolveClosed = resolve; + }); + const state: RemoteTunnelExposure = { + onEvent: callbacks.onEvent, + onClosed: callbacks.onClosed, + closed: false, + closedPromise, + resolveClosed, + }; + const finish = (error?: string) => { + if (state.closed) return; + state.closed = true; + loaded.tunnelExposures.delete(exposureId); + state.resolveClosed(); + state.onClosed(error); + }; + loaded.tunnelExposures.set(exposureId, state); + void send(loaded.child, { + type: "tunnel.open", + exposureId, + providerId, + target, + }).catch((error) => { + finish(describeError(error)); + }); + return { + close: async () => { + if (state.closed) return; + if (loaded.child?.connected) { + await send(loaded.child, { type: "tunnel.close", exposureId }).catch(() => undefined); + } else { + finish(); + return; + } + let timer: ReturnType | undefined; + try { + await Promise.race([ + state.closedPromise, + new Promise((resolve) => { + timer = setTimeout(() => { + finish(); + resolve(); + }, 5_000); + }), + ]); + } finally { + if (timer) clearTimeout(timer); + } + }, + }; + } + fetchUsage(pluginId: string, sourceId: string, input: unknown): Promise { const loaded = this.plugins.get(pluginId); if (!loaded) throw new Error(`Plugin is not available: ${pluginId}`); @@ -989,6 +1102,8 @@ export class PluginRuntime { void send(child, { type: "worktree.cancel", requestId }).catch(() => {}); if (isInstallationRequest(message)) void send(child, { type: "provider.installation.cancel", requestId }).catch(() => {}); + if (message.type === "tunnel.status") + void send(child, { type: "tunnel.status.cancel", requestId }).catch(() => {}); signal?.removeEventListener("abort", cancel); reject(signal?.reason ?? new Error("Plugin request canceled")); }; @@ -1016,6 +1131,8 @@ export class PluginRuntime { void send(child, { type: "provider.installation.cancel", requestId }).catch( () => {}, ); + if (message.type === "tunnel.status") + void send(child, { type: "tunnel.status.cancel", requestId }).catch(() => {}); reject(new Error(`Plugin RPC timed out: ${pluginId}.${message.type}`)); }, timeoutMs); signal?.addEventListener("abort", cancel, { once: true }); @@ -1075,11 +1192,13 @@ export class PluginRuntime { worktreeManager: null, providers: [], usageSources: [], + tunnelProviders: [], child: null, outputCapture: null, pending: new Map(), providerConnections: new Map(), providerConnectionTombstones: new Set(), + tunnelExposures: new Map(), sessionSocket: null, sessionClosed: null, }; @@ -1208,11 +1327,13 @@ export class PluginRuntime { worktreeManager: ready.worktreeManager ?? null, providers: ready.providers ?? [], usageSources: ready.usageSources ?? [], + tunnelProviders: ready.tunnelProviders ?? [], child, outputCapture, pending, providerConnections: new Map(), providerConnectionTombstones: new Set(), + tunnelExposures: new Map(), sessionSocket: session.socket, sessionClosed: sessionAttachment.closed, }; @@ -1292,6 +1413,7 @@ export class PluginRuntime { loaded.worktreeManager = message.worktreeManager; return; } + if (this.handleTunnelMessage(loaded, message)) return; if (message.type === "settings.changed") { this.dependencies.onSettingsChanged?.(loaded.id, message.settingsId); return; @@ -1327,6 +1449,30 @@ export class PluginRuntime { else pending.reject(new Error(message.error)); } + private handleTunnelMessage(loaded: LoadedPlugin, message: PluginProcessMessage): boolean { + if (message.type === "tunnel_providers.changed") { + loaded.tunnelProviders = message.tunnelProviders; + this.dependencies.onTunnelProvidersChanged?.(loaded.id); + return true; + } + if (message.type === "tunnel.event") { + const exposure = loaded.tunnelExposures.get(message.exposureId); + if (exposure && !exposure.closed) exposure.onEvent(message.event); + return true; + } + if (message.type === "tunnel.closed") { + const exposure = loaded.tunnelExposures.get(message.exposureId); + if (exposure && !exposure.closed) { + exposure.closed = true; + loaded.tunnelExposures.delete(message.exposureId); + exposure.resolveClosed(); + exposure.onClosed(message.error); + } + return true; + } + return false; + } + private async handleNotificationSend( loaded: LoadedPlugin, message: Extract, @@ -1652,6 +1798,14 @@ export class PluginRuntime { this.failRemoteProviderConnection(state, new Error(`Plugin process exited: ${loaded.id}`)); } loaded.providerConnections.clear(); + const exposures = [...loaded.tunnelExposures.values()]; + loaded.tunnelExposures.clear(); + for (const exposure of exposures) { + if (exposure.closed) continue; + exposure.closed = true; + exposure.resolveClosed(); + exposure.onClosed(`Plugin process exited: ${loaded.id}`); + } await loaded.sessionClosed; if (wasPublished) this.notify(loaded.id, `Plugin process exited: ${loaded.id}`); } diff --git a/packages/server/src/server/plugins/tunnel-provider.e2e.test.ts b/packages/server/src/server/plugins/tunnel-provider.e2e.test.ts new file mode 100644 index 0000000000..59c1efdfe2 --- /dev/null +++ b/packages/server/src/server/plugins/tunnel-provider.e2e.test.ts @@ -0,0 +1,436 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { + SessionInboundMessage, + SessionOutboundMessage, + TunnelExposure, + TunnelProviderInfo, +} from "@getpaseo/protocol/messages"; +import { afterEach, describe, expect, test } from "vitest"; +import { resolveDaemonVersion } from "../daemon-version.js"; +import { BuiltinPluginLoader } from "./builtin/index.js"; +import { DaemonClient } from "../test-utils/daemon-client.js"; +import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js"; + +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function writeTunnelPlugin(options: { + pluginId: string; + providerId: string; + markerFile: string; +}): Promise { + const dir = await mkdtemp(path.join(tmpdir(), `paseo-${options.pluginId}-`)); + roots.push(dir); + await writeFile( + path.join(dir, "paseo-plugin.json"), + JSON.stringify({ + id: options.pluginId, + requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` }, + }), + ); + await writeFile( + path.join(dir, "index.server.ts"), + `import { appendFileSync } from "node:fs"; +import type { PluginServerContext } from "@getpaseo/plugin/server"; + +const markerFile = ${JSON.stringify(options.markerFile)}; + +export default function contribute(server: PluginServerContext) { + return server.registerTunnelProvider({ + id: ${JSON.stringify(options.providerId)}, + label: "Custom Tunnel", + description: "Subprocess test tunnel provider.", + docsUrl: "https://example.test/docs/tunnel", + async status() { + return { status: "available", detail: "ready-v1" }; + }, + async open(target, { report, signal }) { + appendFileSync(markerFile, "open:" + target.id + ":" + target.host + ":" + target.port + "\\n"); + report({ type: "connecting" }); + await new Promise((resolve) => setTimeout(resolve, 20)); + if (signal.aborted) { + report({ type: "closed", reason: "aborted-early" }); + return; + } + report({ + type: "ready", + url: "https://" + (target.slug ?? target.id) + ".custom-tunnel.test", + stability: "ephemeral", + }); + await new Promise((resolve) => { + if (signal.aborted) { + resolve(); + return; + } + signal.addEventListener("abort", () => resolve(), { once: true }); + }); + appendFileSync(markerFile, "aborted:" + target.id + "\\n"); + report({ type: "closed", reason: "aborted" }); + }, + }); +} +`, + ); + return dir; +} + +function sendRpc( + client: DaemonClient, + message: SessionInboundMessage & { requestId: string }, + expectedType: TResponseType, +): Promise["payload"]> { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + unsubscribe(); + reject(new Error(`Timed out waiting for ${expectedType} (${message.requestId})`)); + }, 15_000); + const unsubscribe = client.subscribeRawMessages((outbound) => { + if (outbound.type === "rpc_error" && outbound.payload.requestId === message.requestId) { + clearTimeout(timer); + unsubscribe(); + const error = new Error(outbound.payload.error) as Error & { code?: string }; + error.code = outbound.payload.code; + reject(error); + return; + } + if ( + outbound.type === expectedType && + "payload" in outbound && + "requestId" in outbound.payload && + outbound.payload.requestId === message.requestId + ) { + clearTimeout(timer); + unsubscribe(); + resolve( + outbound.payload as Extract["payload"], + ); + } + }); + client.sendSessionMessage(message); + }); +} + +describe("pluggable tunnel providers E2E", () => { + test("runs a custom tunnel provider in a plugin subprocess, streams lifecycle events, aborts cleanly, and tears down on reload and disable", async () => { + const markerDir = await mkdtemp(path.join(tmpdir(), "paseo-tunnel-markers-")); + roots.push(markerDir); + const markerFile = path.join(markerDir, "events.log"); + + const daemon = await createTestPaseoDaemon(); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.18.0", + }); + + try { + await client.connect(); + expect(client.getLastServerInfoMessage()?.features?.tunnelProviders).toBe(true); + + await client.patchDaemonConfig({ pluginsEnabled: true }); + const pluginDir = await writeTunnelPlugin({ + pluginId: "custom-tunnel-plugin", + providerId: "custom-tunnel", + markerFile, + }); + await expect(client.installDirectoryPlugin(pluginDir)).resolves.toMatchObject({ + id: "custom-tunnel-plugin", + status: "running", + }); + + // List providers + const providersRes = await sendRpc( + client, + { type: "tunnel.providers.list.request", requestId: "req-providers" }, + "tunnel.providers.list.response", + ); + expect(providersRes.providers).toEqual([ + { + id: "custom-tunnel", + pluginId: "custom-tunnel-plugin", + label: "Custom Tunnel", + description: "Subprocess test tunnel provider.", + docsUrl: "https://example.test/docs/tunnel", + availability: { status: "available", detail: "ready-v1" }, + }, + ]); + + // Observe exposures + const observedEvents: TunnelExposure[] = []; + const unsubscribeRaw = client.subscribeRawMessages((message) => { + if (message.type === "tunnel.exposure.changed") { + observedEvents.push(message.payload.exposure); + } + }); + const initialList = await sendRpc( + client, + { type: "tunnel.exposures.list.request", requestId: "req-observe", observe: true }, + "tunnel.exposures.list.response", + ); + expect(initialList.exposures).toEqual([]); + expect(initialList.subscriptionId).toBeTruthy(); + + // Open exposure + const opened = await sendRpc( + client, + { + type: "tunnel.exposure.open.request", + requestId: "req-open-1", + id: "exp-mcp", + providerId: "custom-tunnel", + host: "127.0.0.1", + port: 4321, + label: "External MCP", + slug: "mcp", + }, + "tunnel.exposure.open.response", + ); + expect(opened.exposure).toMatchObject({ + id: "exp-mcp", + providerId: "custom-tunnel", + target: { host: "127.0.0.1", port: 4321, label: "External MCP", slug: "mcp" }, + state: "ready", + url: "https://mcp.custom-tunnel.test", + stability: "ephemeral", + }); + + // Close exposure explicitly + const closed = await sendRpc( + client, + { + type: "tunnel.exposure.close.request", + requestId: "req-close-1", + exposureId: "exp-mcp", + }, + "tunnel.exposure.close.response", + ); + expect(closed).toEqual({ + requestId: "req-close-1", + exposureId: "exp-mcp", + closed: true, + }); + + // Verify full lifecycle event stream: connecting -> ready -> closed + expect(observedEvents.map((entry) => entry.state)).toEqual(["connecting", "ready", "closed"]); + + const logAfterClose = await readFile(markerFile, "utf8"); + expect(logAfterClose).toContain("open:exp-mcp:127.0.0.1:4321"); + expect(logAfterClose).toContain("aborted:exp-mcp"); + + // Open a second exposure and reload the plugin -> must tear down exposure cleanly + await sendRpc( + client, + { + type: "tunnel.exposure.open.request", + requestId: "req-open-2", + id: "exp-reload", + providerId: "custom-tunnel", + host: "127.0.0.1", + port: 4322, + slug: "svc", + }, + "tunnel.exposure.open.response", + ); + expect(daemon.daemon.tunnelManager.listExposures().map((e) => e.id)).toEqual(["exp-reload"]); + + await client.reloadPlugin("custom-tunnel-plugin"); + expect(daemon.daemon.tunnelManager.listExposures()).toEqual([]); + const logAfterReload = await readFile(markerFile, "utf8"); + expect(logAfterReload).toContain("aborted:exp-reload"); + + // Open a third exposure after reload, then disable plugin -> must tear down and unregister provider + await sendRpc( + client, + { + type: "tunnel.exposure.open.request", + requestId: "req-open-3", + id: "exp-disable", + providerId: "custom-tunnel", + host: "127.0.0.1", + port: 4323, + slug: "svc2", + }, + "tunnel.exposure.open.response", + ); + await client.disablePlugin("custom-tunnel-plugin"); + expect(daemon.daemon.tunnelManager.listExposures()).toEqual([]); + expect( + ( + await sendRpc( + client, + { type: "tunnel.providers.list.request", requestId: "req-providers-after" }, + "tunnel.providers.list.response", + ) + ).providers, + ).toEqual([]); + const logAfterDisable = await readFile(markerFile, "utf8"); + expect(logAfterDisable).toContain("aborted:exp-disable"); + + unsubscribeRaw(); + } finally { + await client.close(); + await daemon.close(); + } + }, 60_000); + + test("enforces tunnel.manage for mutating tunnel RPCs and daemon.read for read RPCs", async () => { + const markerDir = await mkdtemp(path.join(tmpdir(), "paseo-tunnel-auth-")); + roots.push(markerDir); + const markerFile = path.join(markerDir, "events.log"); + + const daemon = await createTestPaseoDaemon(); + const owner = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.18.0", + }); + const reader = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.18.0", + sessionPermissions: ["daemon.read"], + }); + const workspaceOnly = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.18.0", + sessionPermissions: ["workspace.read"], + }); + const tunnelOperator = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.18.0", + sessionPermissions: ["tunnel.manage"], + }); + + try { + await owner.connect(); + await owner.patchDaemonConfig({ pluginsEnabled: true }); + const pluginDir = await writeTunnelPlugin({ + pluginId: "auth-tunnel-plugin", + providerId: "auth-tunnel", + markerFile, + }); + await owner.installDirectoryPlugin(pluginDir); + + await Promise.all([reader.connect(), workspaceOnly.connect(), tunnelOperator.connect()]); + + // daemon.read can list providers and exposures, cannot open/close + const readerProviders = await sendRpc( + reader, + { type: "tunnel.providers.list.request", requestId: "r1" }, + "tunnel.providers.list.response", + ); + expect(readerProviders.providers.map((p) => p.id)).toEqual(["auth-tunnel"]); + + const readerExposures = await sendRpc( + reader, + { type: "tunnel.exposures.list.request", requestId: "r2" }, + "tunnel.exposures.list.response", + ); + expect(readerExposures.exposures).toEqual([]); + + await expect( + sendRpc( + reader, + { + type: "tunnel.exposure.open.request", + requestId: "r3", + providerId: "auth-tunnel", + host: "127.0.0.1", + port: 5000, + }, + "tunnel.exposure.open.response", + ), + ).rejects.toMatchObject({ code: "access_denied" }); + + await expect( + sendRpc( + reader, + { + type: "tunnel.exposure.close.request", + requestId: "r4", + exposureId: "exp-1", + }, + "tunnel.exposure.close.response", + ), + ).rejects.toMatchObject({ code: "access_denied" }); + + // workspace.read is denied on read tunnel RPCs too + await expect( + sendRpc( + workspaceOnly, + { type: "tunnel.providers.list.request", requestId: "w1" }, + "tunnel.providers.list.response", + ), + ).rejects.toMatchObject({ code: "access_denied" }); + + // tunnel.manage can list, open, and close + const opened = await sendRpc( + tunnelOperator, + { + type: "tunnel.exposure.open.request", + requestId: "t1", + id: "exp-auth", + providerId: "auth-tunnel", + host: "127.0.0.1", + port: 5001, + }, + "tunnel.exposure.open.response", + ); + expect(opened.exposure.state).toBe("ready"); + + const closed = await sendRpc( + tunnelOperator, + { + type: "tunnel.exposure.close.request", + requestId: "t2", + exposureId: "exp-auth", + }, + "tunnel.exposure.close.response", + ); + expect(closed.closed).toBe(true); + } finally { + await Promise.all([ + owner.close(), + reader.close(), + workspaceOnly.close(), + tunnelOperator.close(), + ]); + await daemon.close(); + } + }, 60_000); + + test("boots built-in cloudflared-tunnel and tailscale-funnel plugins cleanly without credentials", async () => { + const daemon = await createTestPaseoDaemon({ + pluginsEnabled: false, + builtinPlugins: new BuiltinPluginLoader(undefined, [ + "cloudflared-tunnel", + "tailscale-funnel", + ]), + }); + const client = new DaemonClient({ + url: `ws://127.0.0.1:${daemon.port}/ws`, + appVersion: "0.18.0", + }); + + try { + await client.connect(); + const res = await sendRpc( + client, + { type: "tunnel.providers.list.request", requestId: "builtin-1" }, + "tunnel.providers.list.response", + ); + expect(res.providers.map((provider) => provider.id)).toEqual([ + "cloudflared", + "tailscale-funnel", + ]); + for (const provider of res.providers) { + expect(["available", "unavailable"]).toContain(provider.availability.status); + } + } finally { + await client.close(); + await daemon.close(); + } + }, 60_000); +}); diff --git a/packages/server/src/server/session.ts b/packages/server/src/server/session.ts index a763f59889..f899ee503a 100644 --- a/packages/server/src/server/session.ts +++ b/packages/server/src/server/session.ts @@ -3,6 +3,7 @@ import { type WorkspaceRuntimeStore } from "./workspace-runtime-store/index.js"; import type { AgentMessageBehavior, AgentMessageDelivery } from "./agent/agent-messages/index.js"; import { AgentDirectory, type BackgroundVisibility } from "./agent/directory.js"; import { ConnectedHostSession } from "./connected-hosts/index.js"; +import { TunnelSession, type TunnelManager } from "./tunnels/index.js"; import type { ConnectedHosts } from "./connected-hosts/index.js"; import { createWorkspaceBaseBranchService, @@ -496,6 +497,7 @@ type AgentMcpTransportFactory = () => Promise; export interface SessionOptions { connectedHosts?: ConnectedHosts; + tunnelManager?: TunnelManager; sourceId?: string; routed?: boolean; browserToolsBroker?: BrowserToolsBroker | null; @@ -770,6 +772,7 @@ function resolveAgentSubscriptionSnapshotIds( export class Session { private readonly connectedHostSession: ConnectedHostSession | null; + private readonly tunnelSession: TunnelSession | null; private routed = false; isRouted(): boolean { return this.routed; @@ -998,6 +1001,7 @@ export class Session { this.sessionId = uuidv4(); this.hostSourceId = hostSource(options); this.connectedHostSession = createHostSession(options, this); + this.tunnelSession = createTunnelSession(options, this); this.onMessage = onMessage; this.onMessageToSource = onMessageToSource ? (source, message) => this.observeSourceSend(() => onMessageToSource(source, message)) @@ -2774,9 +2778,13 @@ export class Session { return undefined; } + private dispatchDomainSessionMessage(msg: SessionInboundMessage): Promise | undefined { + return this.connectedHostSession?.dispatch(msg) ?? this.tunnelSession?.dispatch(msg); + } + private async dispatchInboundMessage(msg: SessionInboundMessage, source?: object): Promise { const promise = - this.connectedHostSession?.dispatch(msg) ?? + this.dispatchDomainSessionMessage(msg) ?? this.dispatchSubscriptionMessage(msg, source) ?? this.dispatchVoiceAndControlMessage(msg) ?? this.dispatchAgentObservationMessage(msg, source) ?? @@ -9897,6 +9905,13 @@ function createHostSession(options: SessionOptions, session: Session): Connected ); } +function createTunnelSession(options: SessionOptions, session: Session): TunnelSession | null { + if (!options.tunnelManager) return null; + return new TunnelSession(options.tunnelManager, session.delivery, (message) => + session.publish(message), + ); +} + function hostSource(options: SessionOptions): string { return options.sourceId ?? "owner"; } diff --git a/packages/server/src/server/tunnels/index.ts b/packages/server/src/server/tunnels/index.ts new file mode 100644 index 0000000000..e8fa7fec8d --- /dev/null +++ b/packages/server/src/server/tunnels/index.ts @@ -0,0 +1,10 @@ +export { + TunnelError, + TunnelManager, + type ExposeTunnelInput, + type RegisteredTunnelProvider, + type TunnelErrorCode, + type TunnelHandle, + type TunnelManagerEvent, +} from "./manager.js"; +export { TunnelSession } from "./session.js"; diff --git a/packages/server/src/server/tunnels/manager.test.ts b/packages/server/src/server/tunnels/manager.test.ts new file mode 100644 index 0000000000..a871d4a5ab --- /dev/null +++ b/packages/server/src/server/tunnels/manager.test.ts @@ -0,0 +1,211 @@ +import { describe, expect, it } from "vitest"; +import type { TunnelEvent, TunnelProviderStatus, TunnelTarget } from "@getpaseo/plugin/server"; +import { TunnelError, TunnelManager, type TunnelManagerEvent } from "./manager.js"; + +function createFakeProvider(options: { + id: string; + pluginId: string; + label?: string; + status?: () => Promise; + onOpen?: ( + exposureId: string, + target: TunnelTarget, + callbacks: { + onEvent(event: TunnelEvent): void; + onClosed(error?: string): void; + }, + ) => { close(): Promise }; +}) { + const closedExposures: string[] = []; + const provider = { + id: options.id, + pluginId: options.pluginId, + label: options.label ?? options.id, + status: options.status ?? (async () => ({ status: "available" as const, detail: "ready" })), + open( + exposureId: string, + target: TunnelTarget, + callbacks: { + onEvent(event: TunnelEvent): void; + onClosed(error?: string): void; + }, + ) { + if (options.onOpen) return options.onOpen(exposureId, target, callbacks); + queueMicrotask(() => { + callbacks.onEvent({ type: "connecting" }); + callbacks.onEvent({ + type: "ready", + url: `https://${target.slug ?? exposureId}.example.test`, + stability: "ephemeral", + }); + }); + return { + async close() { + closedExposures.push(exposureId); + callbacks.onEvent({ type: "closed", reason: "requested" }); + callbacks.onClosed(); + }, + }; + }, + }; + return { provider, closedExposures }; +} + +describe("TunnelManager", () => { + it("lists providers with probed availability and isolates per-provider status failures", async () => { + const manager = new TunnelManager(); + manager.registerProvider( + createFakeProvider({ + id: "alpha", + pluginId: "plugin-a", + label: "Alpha", + status: async () => ({ status: "available", detail: "v1.2.3" }), + }).provider, + ); + manager.registerProvider( + createFakeProvider({ + id: "beta", + pluginId: "plugin-b", + label: "Beta", + status: async () => { + throw new Error("CLI probe crashed"); + }, + }).provider, + ); + + const providers = await manager.listProviders(); + expect(providers).toEqual([ + { + id: "alpha", + pluginId: "plugin-a", + label: "Alpha", + availability: { status: "available", detail: "v1.2.3" }, + }, + { + id: "beta", + pluginId: "plugin-b", + label: "Beta", + availability: { status: "unavailable", reason: "CLI probe crashed" }, + }, + ]); + }); + + it("tracks lifecycle transitions from connecting to ready to closed and removes closed exposures", async () => { + const manager = new TunnelManager(); + const { provider, closedExposures } = createFakeProvider({ + id: "demo", + pluginId: "demo-plugin", + }); + manager.registerProvider(provider); + + const events: TunnelManagerEvent[] = []; + const unsubscribe = manager.subscribe((event) => events.push(event)); + + const exposure = await manager.expose({ + id: "exp-1", + providerId: "demo", + host: "127.0.0.1", + port: 4321, + label: "External MCP", + slug: "mcp", + }); + + expect(exposure.state).toBe("ready"); + expect(exposure.url).toBe("https://mcp.example.test"); + expect(exposure.stability).toBe("ephemeral"); + expect(manager.listExposures()).toHaveLength(1); + + await expect(manager.close("exp-1")).resolves.toBe(true); + await expect(manager.close("exp-1")).resolves.toBe(false); + expect(closedExposures).toEqual(["exp-1"]); + expect(manager.listExposures()).toEqual([]); + + const states = events + .filter((event) => event.type === "exposure.changed") + .map((event) => event.exposure.state); + expect(states).toEqual(["connecting", "ready", "closed"]); + unsubscribe(); + }); + + it("tears down active exposures when the owning plugin is unregistered or on closeAll", async () => { + const manager = new TunnelManager(); + const first = createFakeProvider({ id: "p1", pluginId: "plugin-1" }); + const second = createFakeProvider({ id: "p2", pluginId: "plugin-2" }); + manager.registerProvider(first.provider); + manager.registerProvider(second.provider); + + await manager.expose({ id: "e1", providerId: "p1", host: "127.0.0.1", port: 3001 }); + await manager.expose({ id: "e2", providerId: "p2", host: "127.0.0.1", port: 3002 }); + + await manager.unregisterPlugin("plugin-1"); + expect(first.closedExposures).toEqual(["e1"]); + expect(manager.listExposures().map((entry) => entry.id)).toEqual(["e2"]); + + await manager.closeAll(); + expect(second.closedExposures).toEqual(["e2"]); + expect(manager.listExposures()).toEqual([]); + }); + + it("rejects expose when provider fails before ready and leaves no leaked exposure", async () => { + const manager = new TunnelManager(); + manager.registerProvider( + createFakeProvider({ + id: "failing", + pluginId: "failing-plugin", + onOpen(_exposureId, _target, callbacks) { + queueMicrotask(() => { + callbacks.onClosed("All 3 Funnel ports are in use"); + }); + return { close: async () => undefined }; + }, + }).provider, + ); + + await expect( + manager.expose({ providerId: "failing", host: "127.0.0.1", port: 8080 }), + ).rejects.toMatchObject({ + code: "open_failed", + message: "All 3 Funnel ports are in use", + }); + expect(manager.listExposures()).toEqual([]); + }); + + it("rejects duplicate provider IDs and invalid targets", async () => { + const manager = new TunnelManager(); + manager.registerProvider(createFakeProvider({ id: "dup", pluginId: "p1" }).provider); + expect(() => + manager.registerProvider(createFakeProvider({ id: "dup", pluginId: "p2" }).provider), + ).toThrow(TunnelError); + + await expect( + manager.expose({ providerId: "missing", host: "127.0.0.1", port: 8080 }), + ).rejects.toMatchObject({ code: "provider_not_found" }); + + await expect( + manager.expose({ providerId: "dup", host: "127.0.0.1", port: 0 }), + ).rejects.toMatchObject({ code: "invalid_target" }); + + for (const badHost of [ + "", + " ", + "127.0.0.1:8080", + "localhost:3000", + "http://127.0.0.1", + "127.0.0.1/path", + "127.0.0.1?q=1", + "127.0.0.1#frag", + "user@127.0.0.1", + "local host", + "[::1]:8080", + "[not-an-ip]", + ]) { + await expect( + manager.expose({ providerId: "dup", host: badHost, port: 8080 }), + ).rejects.toMatchObject({ code: "invalid_target" }); + } + + const ipv6 = await manager.expose({ id: "exp-v6", providerId: "dup", host: "::1", port: 8080 }); + expect(ipv6.target.host).toBe("::1"); + await manager.close("exp-v6"); + }); +}); diff --git a/packages/server/src/server/tunnels/manager.ts b/packages/server/src/server/tunnels/manager.ts new file mode 100644 index 0000000000..00b4130649 --- /dev/null +++ b/packages/server/src/server/tunnels/manager.ts @@ -0,0 +1,518 @@ +import { randomUUID } from "node:crypto"; +import { isIP } from "node:net"; +import type { + TunnelEvent, + TunnelProviderStatus, + TunnelStability, + TunnelTarget, +} from "@getpaseo/plugin/server"; +import type { TunnelExposure, TunnelProviderInfo } from "@getpaseo/protocol/tunnels"; +import type pino from "pino"; + +const DEFAULT_READY_TIMEOUT_MS = 30_000; + +export type TunnelErrorCode = + | "provider_not_found" + | "provider_duplicate" + | "exposure_duplicate" + | "invalid_target" + | "open_failed" + | "open_timeout" + | "aborted"; + +export class TunnelError extends Error { + constructor( + readonly code: TunnelErrorCode, + message: string, + options?: { cause?: unknown }, + ) { + super(message, options); + this.name = "TunnelError"; + } +} + +export interface TunnelHandle { + close(): Promise; +} + +export interface RegisteredTunnelProvider { + readonly id: string; + readonly pluginId: string; + readonly label: string; + readonly description?: string; + readonly docsUrl?: string; + status(options?: { signal?: AbortSignal }): Promise; + open( + exposureId: string, + target: TunnelTarget, + callbacks: { + onEvent(event: TunnelEvent): void; + onClosed(error?: string): void; + }, + ): TunnelHandle; +} + +export interface ExposeTunnelInput { + id?: string; + providerId: string; + host: string; + port: number; + label?: string; + slug?: string; + waitForReady?: boolean; + readyTimeoutMs?: number; + signal?: AbortSignal; +} + +export type TunnelManagerEvent = + | { type: "exposure.changed"; exposure: TunnelExposure } + | { type: "providers.changed" }; + +interface ActiveExposure { + snapshot: TunnelExposure; + handle: TunnelHandle | null; + closed: boolean; + closing: Promise | null; + lastClosedReason: string | null; + resolveReady: (exposure: TunnelExposure) => void; + rejectReady: (error: Error) => void; + readySettled: boolean; +} + +function cloneExposure(exposure: TunnelExposure): TunnelExposure { + return { + ...exposure, + target: { ...exposure.target }, + }; +} + +const HOSTNAME_PATTERN = + /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i; + +function isValidTargetHost(host: string): boolean { + if (!host || host.length > 253) return false; + if (/[\s/\\?#@]/.test(host)) return false; + if (host.startsWith("[") || host.endsWith("]")) { + if (!host.startsWith("[") || !host.endsWith("]")) return false; + return isIP(host.slice(1, -1)) === 6; + } + if (isIP(host) !== 0) return true; + if (host.includes(":")) return false; + return HOSTNAME_PATTERN.test(host); +} + +function isHttpUrl(value: string): boolean { + try { + const parsed = new URL(value); + return parsed.protocol === "https:" || parsed.protocol === "http:"; + } catch { + return false; + } +} + +function describeError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export class TunnelManager { + private readonly providers = new Map(); + private readonly exposures = new Map(); + private readonly listeners = new Set<(event: TunnelManagerEvent) => void>(); + private readonly logger: pino.Logger | null; + private readonly now: () => Date; + + constructor(options?: { logger?: pino.Logger; now?: () => Date }) { + this.logger = options?.logger?.child({ module: "tunnels" }) ?? null; + this.now = options?.now ?? (() => new Date()); + } + + subscribe(listener: (event: TunnelManagerEvent) => void): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + registerProvider(provider: RegisteredTunnelProvider): void { + const id = provider.id.trim(); + if (!id) { + throw new TunnelError("invalid_target", "Tunnel provider ID is required"); + } + if (this.providers.has(id)) { + throw new TunnelError("provider_duplicate", `Tunnel provider "${id}" is already registered`); + } + this.providers.set(id, { ...provider, id }); + this.emit({ type: "providers.changed" }); + } + + async unregisterProvider(providerId: string): Promise { + if (!this.providers.delete(providerId)) return; + const affected = [...this.exposures.values()] + .filter((entry) => entry.snapshot.providerId === providerId) + .map((entry) => entry.snapshot.id); + await Promise.allSettled(affected.map((id) => this.close(id))); + this.emit({ type: "providers.changed" }); + } + + async unregisterPlugin(pluginId: string): Promise { + const owned = [...this.providers.values()] + .filter((provider) => provider.pluginId === pluginId) + .map((provider) => provider.id); + if (owned.length === 0) return; + for (const id of owned) { + this.providers.delete(id); + } + const ownedSet = new Set(owned); + const affected = [...this.exposures.values()] + .filter((entry) => ownedSet.has(entry.snapshot.providerId)) + .map((entry) => entry.snapshot.id); + await Promise.allSettled(affected.map((id) => this.close(id))); + this.emit({ type: "providers.changed" }); + } + + async syncPluginProviders( + pluginId: string, + nextProviders: readonly RegisteredTunnelProvider[], + ): Promise { + const currentOwned = [...this.providers.values()].filter( + (provider) => provider.pluginId === pluginId, + ); + const nextIds = new Set(nextProviders.map((provider) => provider.id)); + const removedIds = currentOwned.map((provider) => provider.id).filter((id) => !nextIds.has(id)); + + for (const id of removedIds) { + this.providers.delete(id); + } + for (const next of nextProviders) { + const existing = this.providers.get(next.id); + if (existing && existing.pluginId !== pluginId) { + this.logger?.warn( + { pluginId, providerId: next.id, ownerPluginId: existing.pluginId }, + "Ignoring duplicate tunnel provider ID from another plugin", + ); + continue; + } + this.providers.set(next.id, next); + } + if (removedIds.length > 0) { + const removedSet = new Set(removedIds); + const affected = [...this.exposures.values()] + .filter((entry) => removedSet.has(entry.snapshot.providerId)) + .map((entry) => entry.snapshot.id); + await Promise.allSettled(affected.map((id) => this.close(id))); + } + this.emit({ type: "providers.changed" }); + } + + async listProviders(options?: { signal?: AbortSignal }): Promise { + const registered = [...this.providers.values()].sort((left, right) => + left.id.localeCompare(right.id), + ); + return Promise.all( + registered.map(async (provider): Promise => { + let availability: TunnelProviderStatus; + try { + availability = await provider.status({ signal: options?.signal }); + } catch (error) { + availability = { + status: "unavailable", + reason: describeError(error), + }; + } + const info: TunnelProviderInfo = { + id: provider.id, + pluginId: provider.pluginId, + label: provider.label, + availability, + }; + if (provider.description !== undefined) info.description = provider.description; + if (provider.docsUrl !== undefined) info.docsUrl = provider.docsUrl; + return info; + }), + ); + } + + listExposures(): TunnelExposure[] { + return [...this.exposures.values()] + .map((entry) => cloneExposure(entry.snapshot)) + .sort( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ); + } + + getExposure(exposureId: string): TunnelExposure | null { + const entry = this.exposures.get(exposureId); + return entry ? cloneExposure(entry.snapshot) : null; + } + + async expose(input: ExposeTunnelInput): Promise { + const providerId = input.providerId.trim(); + const provider = this.providers.get(providerId); + if (!provider) { + throw new TunnelError("provider_not_found", `Unknown tunnel provider: ${providerId}`); + } + const host = input.host.trim(); + if (!isValidTargetHost(host)) { + throw new TunnelError( + "invalid_target", + `Tunnel target host must be a valid hostname or IP address (got "${input.host}")`, + ); + } + if (!Number.isInteger(input.port) || input.port < 1 || input.port > 65535) { + throw new TunnelError( + "invalid_target", + `Tunnel target port must be an integer between 1 and 65535 (got ${input.port})`, + ); + } + const id = input.id !== undefined ? input.id.trim() : `tun_${randomUUID()}`; + if (!id) { + throw new TunnelError("invalid_target", "Tunnel exposure ID must not be empty"); + } + if (this.exposures.has(id)) { + throw new TunnelError("exposure_duplicate", `Tunnel exposure "${id}" is already active`); + } + if (input.signal?.aborted) { + throw new TunnelError("aborted", "Tunnel exposure request was aborted"); + } + + const timestamp = this.now().toISOString(); + const target: TunnelTarget = { + id, + host, + port: input.port, + ...(input.label !== undefined ? { label: input.label } : {}), + ...(input.slug !== undefined ? { slug: input.slug } : {}), + }; + + let resolveReady!: (exposure: TunnelExposure) => void; + let rejectReady!: (error: Error) => void; + const readyPromise = new Promise((resolve, reject) => { + resolveReady = resolve; + rejectReady = reject; + }); + // Prevent unhandled rejections if waitForReady is false or callers drop out early. + void readyPromise.catch(() => undefined); + + const entry: ActiveExposure = { + snapshot: { + id, + providerId: provider.id, + target: { + host, + port: input.port, + ...(input.label !== undefined ? { label: input.label } : {}), + ...(input.slug !== undefined ? { slug: input.slug } : {}), + }, + state: "connecting", + url: null, + stability: null, + detail: null, + error: null, + createdAt: timestamp, + updatedAt: timestamp, + }, + handle: null, + closed: false, + closing: null, + lastClosedReason: null, + resolveReady, + rejectReady, + readySettled: false, + }; + + this.exposures.set(id, entry); + this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) }); + + try { + entry.handle = provider.open(id, target, { + onEvent: (event) => this.handleProviderEvent(entry, event), + onClosed: (error) => this.handleProviderClosed(entry, error), + }); + } catch (error) { + const message = describeError(error); + this.finalizeExposure(entry, { error: message }); + throw new TunnelError("open_failed", message, { cause: error }); + } + + if (input.waitForReady === false) { + return cloneExposure(entry.snapshot); + } + + const timeoutMs = input.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS; + return await new Promise((resolve, reject) => { + const cleanup = () => { + if (timer) clearTimeout(timer); + input.signal?.removeEventListener("abort", onAbort); + }; + const onAbort = () => { + cleanup(); + void this.close(id); + reject(new TunnelError("aborted", "Tunnel exposure request was aborted")); + }; + const timer = setTimeout(() => { + cleanup(); + void this.close(id); + reject( + new TunnelError( + "open_timeout", + `Timed out waiting for tunnel provider "${provider.id}" to become ready`, + ), + ); + }, timeoutMs); + input.signal?.addEventListener("abort", onAbort, { once: true }); + readyPromise.then( + (exposure) => { + cleanup(); + resolve(exposure); + return undefined; + }, + (error) => { + cleanup(); + reject(error); + return undefined; + }, + ); + }); + } + + async close(exposureId: string): Promise { + const entry = this.exposures.get(exposureId); + if (!entry) return false; + if (entry.closing) { + await entry.closing; + return true; + } + const closing = (async () => { + try { + await entry.handle?.close(); + } catch (error) { + this.logger?.warn({ err: error, exposureId }, "Tunnel handle close failed"); + } finally { + this.finalizeExposure(entry, {}); + } + })(); + entry.closing = closing; + await closing; + return true; + } + + async closeAll(): Promise { + const ids = [...this.exposures.keys()]; + await Promise.allSettled(ids.map((id) => this.close(id))); + } + + private handleProviderEvent(entry: ActiveExposure, event: TunnelEvent): void { + if (entry.closed) return; + const timestamp = this.now().toISOString(); + + if (event.type === "connecting") { + const detail = event.detail ?? null; + if (entry.snapshot.state === "connecting" && entry.snapshot.detail === detail) return; + entry.snapshot = { + ...entry.snapshot, + state: "connecting", + detail, + updatedAt: timestamp, + }; + this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) }); + return; + } + + if (event.type === "ready") { + if (!isHttpUrl(event.url)) { + const message = `Tunnel provider "${entry.snapshot.providerId}" reported invalid URL: ${event.url}`; + this.finalizeExposure(entry, { error: message }); + void entry.handle?.close().catch(() => undefined); + return; + } + const stability: TunnelStability | null = event.stability ?? null; + entry.snapshot = { + ...entry.snapshot, + state: "ready", + url: event.url, + stability, + detail: event.detail ?? null, + error: null, + updatedAt: timestamp, + }; + const snapshot = cloneExposure(entry.snapshot); + this.emit({ type: "exposure.changed", exposure: snapshot }); + if (!entry.readySettled) { + entry.readySettled = true; + entry.resolveReady(snapshot); + } + return; + } + + if (event.type === "reconnecting") { + entry.snapshot = { + ...entry.snapshot, + state: "reconnecting", + detail: event.reason ?? null, + updatedAt: timestamp, + }; + this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) }); + return; + } + + if (event.type === "error") { + entry.snapshot = { + ...entry.snapshot, + state: "error", + error: event.message, + updatedAt: timestamp, + }; + this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) }); + if (event.recoverable !== true && !entry.readySettled) { + entry.readySettled = true; + entry.rejectReady(new TunnelError("open_failed", event.message)); + } + return; + } + + if (event.type === "closed") { + entry.lastClosedReason = event.reason ?? null; + this.finalizeExposure(entry, { reason: event.reason }); + } + } + + private handleProviderClosed(entry: ActiveExposure, error?: string): void { + this.finalizeExposure(entry, { error }); + } + + private finalizeExposure( + entry: ActiveExposure, + options: { reason?: string; error?: string }, + ): void { + if (entry.closed) return; + entry.closed = true; + this.exposures.delete(entry.snapshot.id); + const error = options.error ?? entry.snapshot.error; + const detail = options.reason ?? entry.lastClosedReason ?? entry.snapshot.detail; + entry.snapshot = { + ...entry.snapshot, + state: "closed", + detail, + error, + updatedAt: this.now().toISOString(), + }; + this.emit({ type: "exposure.changed", exposure: cloneExposure(entry.snapshot) }); + if (!entry.readySettled) { + entry.readySettled = true; + entry.rejectReady( + new TunnelError("open_failed", error ?? "Tunnel closed before becoming ready"), + ); + } + } + + private emit(event: TunnelManagerEvent): void { + for (const listener of this.listeners) { + try { + listener(event); + } catch (error) { + this.logger?.warn({ err: error }, "Tunnel manager listener failed"); + } + } + } +} diff --git a/packages/server/src/server/tunnels/session.ts b/packages/server/src/server/tunnels/session.ts new file mode 100644 index 0000000000..bb3388f372 --- /dev/null +++ b/packages/server/src/server/tunnels/session.ts @@ -0,0 +1,129 @@ +import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages"; +import type { SessionDelivery } from "../session/owned-subscriptions/index.js"; +import { TunnelError, type TunnelManager } from "./manager.js"; + +type TunnelRequest = Extract< + SessionInboundMessage, + { type: T } +>; + +/** Adapts daemon TunnelManager capabilities to source-owned session delivery. */ +export class TunnelSession { + constructor( + private readonly tunnels: Pick< + TunnelManager, + "listProviders" | "listExposures" | "expose" | "close" | "subscribe" + >, + private readonly delivery: SessionDelivery, + private readonly emit: (message: SessionOutboundMessage) => void, + ) {} + + dispatch(message: SessionInboundMessage): Promise | undefined { + if (!message.type.startsWith("tunnel.")) return; + return this.handle(message); + } + + private async handle(message: SessionInboundMessage): Promise { + try { + await this.execute(message); + } catch (error) { + this.fail(message, error); + } + } + + private fail(message: SessionInboundMessage, error: unknown): void { + if (!("requestId" in message) || !message.requestId) return; + const code = error instanceof TunnelError ? error.code : "tunnel_error"; + const text = error instanceof Error ? error.message : String(error); + this.emit({ + type: "rpc_error", + payload: { + requestId: message.requestId, + requestType: message.type, + code, + error: text, + }, + }); + } + + private async execute(message: SessionInboundMessage): Promise { + switch (message.type) { + case "tunnel.providers.list.request": + this.emit({ + type: "tunnel.providers.list.response", + payload: { + requestId: message.requestId, + providers: await this.tunnels.listProviders({ signal: this.delivery.requestSignal }), + }, + }); + return; + case "tunnel.exposures.list.request": + return this.listExposures(message); + case "tunnel.exposure.open.request": { + const exposure = await this.tunnels.expose({ + id: message.id, + providerId: message.providerId, + host: message.host, + port: message.port, + label: message.label, + slug: message.slug, + signal: this.delivery.requestSignal, + }); + this.emit({ + type: "tunnel.exposure.open.response", + payload: { requestId: message.requestId, exposure }, + }); + return; + } + case "tunnel.exposure.close.request": { + const closed = await this.tunnels.close(message.exposureId); + this.emit({ + type: "tunnel.exposure.close.response", + payload: { + requestId: message.requestId, + exposureId: message.exposureId, + closed, + }, + }); + return; + } + } + } + + private async listExposures( + message: TunnelRequest<"tunnel.exposures.list.request">, + ): Promise { + if (!message.observe) { + this.emit({ + type: "tunnel.exposures.list.response", + payload: { + requestId: message.requestId, + exposures: this.tunnels.listExposures(), + }, + }); + return; + } + let stop = () => {}; + const owner = this.delivery.begin("tunnels", undefined, () => stop()); + try { + stop = this.tunnels.subscribe((event) => { + if (event.type !== "exposure.changed") return; + owner.emit({ + type: "tunnel.exposure.changed", + payload: { subscriptionId: owner.id, exposure: event.exposure }, + }); + }); + this.emit({ + type: "tunnel.exposures.list.response", + payload: { + requestId: message.requestId, + subscriptionId: owner.id, + exposures: this.tunnels.listExposures(), + }, + }); + } catch (error) { + await owner.release(); + throw error; + } + } +} diff --git a/packages/server/src/server/websocket-server.ts b/packages/server/src/server/websocket-server.ts index f66c80e28b..d7e3c15464 100644 --- a/packages/server/src/server/websocket-server.ts +++ b/packages/server/src/server/websocket-server.ts @@ -15,6 +15,7 @@ import { createToolHosts } from "./agent/host-operations/index.js"; import { HOST_ROUTE_OPCODE } from "@getpaseo/protocol/binary-frames/index"; import { DaemonLinkEndpoint, VirtualHostSocket } from "./connected-hosts/index.js"; import { ConnectedHosts } from "./connected-hosts/index.js"; +import type { TunnelManager } from "./tunnels/index.js"; import { stat } from "node:fs/promises"; import { createWorkspaceBaseBranchService, @@ -680,6 +681,7 @@ export class VoiceAssistantWebSocketServer { private readonly advertiseRelayConfig: boolean; private readonly directorySync = new DirectorySyncService(); private readonly pluginRuntime: SessionOptions["pluginRuntime"]; + private readonly tunnelManager: TunnelManager | null; private readonly orchestrationSkills: SessionOptions["orchestrationSkills"]; private async validateCompletedCreation(snapshot: CreationSnapshot): Promise { @@ -750,6 +752,7 @@ export class VoiceAssistantWebSocketServer { workspaceLabelService?: WorkspaceLabelService, workspaceArchiveOperations?: WorkspaceArchiveOperations, pushNotifications?: PushNotifications, + tunnelManager?: TunnelManager | null, ) { this.logger = logger.child({ module: "websocket-server" }); this.workspaceSetupRuntime = workspaceSetupRuntime; @@ -767,6 +770,7 @@ export class VoiceAssistantWebSocketServer { this.browserToolsBroker = browserToolsBroker ?? null; this.hubRelationships = hubRelationships ?? null; this.pluginRuntime = pluginRuntime; + this.tunnelManager = tunnelManager ?? null; this.orchestrationSkills = orchestrationSkills; this.agentManager = agentManager; this.agentStorage = agentStorage; @@ -1725,6 +1729,7 @@ export class VoiceAssistantWebSocketServer { private createSocketSession(options: SocketSessionOptions): Session { return new Session({ connectedHosts: this.connectedHosts, + tunnelManager: this.tunnelManager ?? undefined, getSourceLocalEndpoint: (source) => this.socketLocalEndpoints.get(source), getConnectedHostBufferedAmount: () => { let total = 0; @@ -2208,6 +2213,8 @@ export class VoiceAssistantWebSocketServer { pluginSubscriptions: true, // COMPAT(pluginNotifications): added in v0.18.0, remove gate after 2027-06-01. pluginNotifications: true, + // COMPAT(tunnelProviders): added in v0.18.0, remove gate after 2027-06-01. + ...(this.tunnelManager ? { tunnelProviders: true } : {}), // COMPAT(skillManagement): added in v0.4.0, remove gate after 2027-08-16. skillManagement: true, // COMPAT(idleRuntimeCleanupSetting): added in v0.13.0, remove gate after 2027-04-26. diff --git a/plugin-examples/tunnel-provider/README.md b/plugin-examples/tunnel-provider/README.md new file mode 100644 index 0000000000..24197d8493 --- /dev/null +++ b/plugin-examples/tunnel-provider/README.md @@ -0,0 +1,15 @@ +# Custom tunnel provider example + +Registers a tunnel provider with `server.registerTunnelProvider()`. + +## What it does + +- Probes the local CLI in `status()` and returns `available` or `unavailable` with install guidance. +- Spawns the tunnel process in `open(target, { report, signal })`, parses the public HTTPS URL, and reports `connecting`, `ready`, and `closed` events. +- Terminates the child process cleanly when `signal` aborts. + +## Install + +```bash +paseo plugin install /absolute/path/to/plugin-examples/tunnel-provider +``` diff --git a/plugin-examples/tunnel-provider/index.server.ts b/plugin-examples/tunnel-provider/index.server.ts new file mode 100644 index 0000000000..a8ee17b4e0 --- /dev/null +++ b/plugin-examples/tunnel-provider/index.server.ts @@ -0,0 +1,6 @@ +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { createCustomTunnelProvider } from "./server/tunnel"; + +export default function contribute(server: PluginServerContext) { + return server.registerTunnelProvider(createCustomTunnelProvider()); +} diff --git a/plugin-examples/tunnel-provider/paseo-plugin.json b/plugin-examples/tunnel-provider/paseo-plugin.json new file mode 100644 index 0000000000..89bac16f6f --- /dev/null +++ b/plugin-examples/tunnel-provider/paseo-plugin.json @@ -0,0 +1,6 @@ +{ + "id": "tunnel-provider", + "name": "Custom tunnel provider", + "description": "Expose local HTTP endpoints through a custom tunnel binary.", + "requirements": { "paseo": ">=0.18.0" } +} diff --git a/plugin-examples/tunnel-provider/server/tunnel.ts b/plugin-examples/tunnel-provider/server/tunnel.ts new file mode 100644 index 0000000000..6569edac80 --- /dev/null +++ b/plugin-examples/tunnel-provider/server/tunnel.ts @@ -0,0 +1,85 @@ +import { + execCommand, + spawnProcess, + terminateProcess, + type TunnelProviderRegistration, +} from "@getpaseo/plugin/server"; + +const URL_PATTERN = /https:\/\/[a-z0-9.-]+/i; + +function formatHostForUrl(host: string): string { + return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; +} + +export function createCustomTunnelProvider(): TunnelProviderRegistration { + const binary = process.env.CUSTOM_TUNNEL_BIN || "custom-tunnel"; + + return { + id: "custom-tunnel", + label: "Custom Tunnel", + description: "Expose a local HTTP host and port through a custom CLI.", + docsUrl: "https://example.com/docs/custom-tunnel", + + async status({ signal }) { + try { + const { stdout } = await execCommand(binary, ["--version"], { signal, timeout: 5_000 }); + return { status: "available", detail: stdout.trim() || undefined }; + } catch { + return { + status: "unavailable", + reason: `${binary} is not installed or not on PATH.`, + installUrl: "https://example.com/install", + fixHint: `Install ${binary} or set CUSTOM_TUNNEL_BIN in the daemon environment.`, + }; + } + }, + + async open(target, { report, signal }) { + report({ type: "connecting" }); + + const child = spawnProcess( + binary, + ["http", `${formatHostForUrl(target.host)}:${target.port}`], + { + stdio: "pipe", + }, + ); + + let ready = false; + const onOutput = (chunk: Buffer | string) => { + if (ready || signal.aborted) return; + const match = URL_PATTERN.exec(String(chunk)); + if (!match) return; + ready = true; + report({ type: "ready", url: match[0], stability: "ephemeral" }); + }; + + child.stdout.on("data", onOutput); + child.stderr.on("data", onOutput); + + const onAbort = () => { + void terminateProcess(child, "SIGTERM").catch(() => undefined); + }; + signal.addEventListener("abort", onAbort, { once: true }); + if (signal.aborted) onAbort(); + + try { + const code = await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", (exitCode) => resolve(exitCode)); + }); + + if (signal.aborted) { + report({ type: "closed", reason: "aborted" }); + return; + } + if (!ready || (code !== null && code !== 0)) { + throw new Error(`${binary} exited with code ${code ?? "null"}`); + } + report({ type: "closed" }); + } finally { + signal.removeEventListener("abort", onAbort); + } + }, + }; +} diff --git a/plugins/cloudflared-tunnel/index.server.ts b/plugins/cloudflared-tunnel/index.server.ts new file mode 100644 index 0000000000..f56acae15e --- /dev/null +++ b/plugins/cloudflared-tunnel/index.server.ts @@ -0,0 +1,14 @@ +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { createCloudflaredTunnelProvider } from "./server/cloudflared.js"; +import { cloudflaredSettings, type CloudflaredSettings } from "./shared/settings.js"; + +export default function contribute(server: PluginServerContext) { + const settings = server.registerSettings(cloudflaredSettings); + + const readSettings = async (): Promise => { + const state = await settings.read(); + return state.status === "ready" ? state.values : {}; + }; + + return server.registerTunnelProvider(createCloudflaredTunnelProvider({ readSettings })); +} diff --git a/plugins/cloudflared-tunnel/paseo-plugin.json b/plugins/cloudflared-tunnel/paseo-plugin.json new file mode 100644 index 0000000000..8355ea362a --- /dev/null +++ b/plugins/cloudflared-tunnel/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "cloudflared-tunnel", "requirements": { "paseo": ">=0.17.6" } } diff --git a/plugins/cloudflared-tunnel/server/cloudflared.ts b/plugins/cloudflared-tunnel/server/cloudflared.ts new file mode 100644 index 0000000000..0ee9e218bc --- /dev/null +++ b/plugins/cloudflared-tunnel/server/cloudflared.ts @@ -0,0 +1,292 @@ +import { + execCommand, + spawnProcess, + terminateProcess, + type TunnelProviderRegistration, + type TunnelProviderStatus, +} from "@getpaseo/plugin/server"; +import type { CloudflaredSettings } from "../shared/settings.js"; + +const CLOUDFLARED_INSTALL_URL = + "https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"; +const CLOUDFLARED_DOCS_URL = + "https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/"; +const QUICK_TUNNEL_URL_PATTERN = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/i; +const NAMED_TUNNEL_READY_PATTERN = /registered tunnel connection|connection\s+\S+\s+registered/i; +const FORCE_KILL_DELAY_MS = 2_000; + +export interface CloudflaredProviderOptions { + readSettings?: () => Promise; + env?: NodeJS.ProcessEnv; +} + +function formatHostForUrl(host: string): string { + return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; +} + +function normalizeHttpUrl(raw: string): string | null { + try { + const parsed = new URL(raw.trim()); + if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null; + return parsed.toString().replace(/\/+$/, ""); + } catch { + return null; + } +} + +function firstLine(text: string): string | undefined { + const line = text + .split(/\r?\n/) + .map((entry) => entry.trim()) + .find((entry) => entry.length > 0); + return line; +} + +function redactSecret(text: string, secret?: string): string { + if (!secret) return text; + return text.split(secret).join("[REDACTED]"); +} + +function isNotFoundError(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error.code === "ENOENT" || error.code === "ENOTDIR") + ); +} + +export function createCloudflaredTunnelProvider( + options: CloudflaredProviderOptions = {}, +): TunnelProviderRegistration { + const readSettings: () => Promise = + options.readSettings ?? (async () => ({})); + const env = options.env; + + async function resolveConfig(): Promise<{ + binary: string; + tunnelToken?: string; + publicBaseUrl?: string; + configError?: { reason: string; fixHint: string }; + }> { + const values = await readSettings(); + const binary = values.binaryPath?.trim() || "cloudflared"; + const tunnelToken = values.tunnelToken?.trim() || undefined; + const rawPublicBaseUrl = values.publicBaseUrl?.trim() || undefined; + + if (tunnelToken && !rawPublicBaseUrl) { + return { + binary, + tunnelToken, + configError: { + reason: "Named Cloudflare Tunnel requires publicBaseUrl when tunnelToken is set.", + fixHint: + "Set publicBaseUrl in Cloudflare Tunnel settings, or clear tunnelToken to use quick tunnels.", + }, + }; + } + + if (rawPublicBaseUrl) { + const normalized = normalizeHttpUrl(rawPublicBaseUrl); + if (!normalized) { + return { + binary, + tunnelToken, + configError: { + reason: `Invalid publicBaseUrl "${rawPublicBaseUrl}". Expected an http(s) URL.`, + fixHint: "Update publicBaseUrl to a valid https:// URL.", + }, + }; + } + return { binary, tunnelToken, publicBaseUrl: normalized }; + } + + return { binary, tunnelToken }; + } + + return { + id: "cloudflared", + label: "Cloudflare Tunnel", + description: + "Expose local HTTP targets directly with Cloudflare quick tunnels, or run a remotely configured named tunnel.", + docsUrl: CLOUDFLARED_DOCS_URL, + + async status({ signal }): Promise { + const config = await resolveConfig(); + if (config.configError) { + return { + status: "unavailable", + reason: config.configError.reason, + fixHint: config.configError.fixHint, + }; + } + try { + const { stdout, stderr } = await execCommand(config.binary, ["--version"], { + env, + signal, + timeout: 5_000, + }); + const version = firstLine(stdout) ?? firstLine(stderr); + const mode = config.tunnelToken ? "named tunnel" : "quick tunnel"; + return { + status: "available", + detail: version ? `${version} (${mode})` : mode, + }; + } catch (error) { + if (isNotFoundError(error)) { + return { + status: "unavailable", + reason: `${config.binary} is not installed or not on PATH.`, + installUrl: CLOUDFLARED_INSTALL_URL, + fixHint: "Install cloudflared and make sure it is available on PATH.", + }; + } + return { + status: "unavailable", + reason: `Failed to query ${config.binary}: ${error instanceof Error ? error.message : String(error)}`, + installUrl: CLOUDFLARED_INSTALL_URL, + fixHint: "Verify that cloudflared runs cleanly from your shell.", + }; + } + }, + + async open(target, { report, signal }): Promise { + const config = await resolveConfig(); + if (config.configError) { + throw new Error(config.configError.reason); + } + + const targetUrl = `http://${formatHostForUrl(target.host)}:${target.port}`; + const isNamed = Boolean(config.tunnelToken && config.publicBaseUrl); + const args = isNamed + ? ["tunnel", "--no-autoupdate", "run"] + : ["tunnel", "--no-autoupdate", "--url", targetUrl]; + const spawnEnv = isNamed + ? { ...(env ?? process.env), TUNNEL_TOKEN: config.tunnelToken! } + : env; + + report({ type: "connecting" }); + + const child = spawnProcess(config.binary, args, { + env: spawnEnv, + stdio: "pipe", + }); + + let readyReported = false; + let exited = false; + let lastOutputLine = ""; + let forceKillTimer: ReturnType | null = null; + let stdoutRemainder = ""; + let stderrRemainder = ""; + + const stopChild = () => { + if (exited) return; + void terminateProcess(child, "SIGTERM").catch(() => undefined); + if (!forceKillTimer) { + forceKillTimer = setTimeout(() => { + if (!exited) { + void terminateProcess(child, "SIGKILL").catch(() => undefined); + } + }, FORCE_KILL_DELAY_MS); + } + }; + + const processLine = (rawLine: string) => { + const line = rawLine.trim(); + if (!line) return; + lastOutputLine = redactSecret(line, config.tunnelToken); + if (readyReported || signal.aborted) return; + + if (isNamed) { + if (NAMED_TUNNEL_READY_PATTERN.test(line)) { + readyReported = true; + report({ + type: "ready", + url: config.publicBaseUrl!, + stability: "stable", + }); + } + return; + } + + const match = QUICK_TUNNEL_URL_PATTERN.exec(line); + if (match) { + readyReported = true; + report({ + type: "ready", + url: match[0], + stability: "ephemeral", + }); + } + }; + + const consumeChunk = (stream: "stdout" | "stderr", chunk: Buffer | string) => { + const text = (stream === "stdout" ? stdoutRemainder : stderrRemainder) + String(chunk); + const lines = text.split(/\r?\n/); + const remainder = lines.pop() ?? ""; + if (stream === "stdout") stdoutRemainder = remainder; + else stderrRemainder = remainder; + for (const line of lines) processLine(line); + }; + + child.stdout.on("data", (chunk) => consumeChunk("stdout", chunk)); + child.stderr.on("data", (chunk) => consumeChunk("stderr", chunk)); + + const onAbort = () => stopChild(); + signal.addEventListener("abort", onAbort, { once: true }); + if (signal.aborted) stopChild(); + + try { + const result = await new Promise<{ + code: number | null; + exitSignal: NodeJS.Signals | null; + spawnError?: Error; + }>((resolve) => { + child.once("error", (error) => { + exited = true; + resolve({ code: null, exitSignal: null, spawnError: error }); + }); + child.once("close", (code, exitSignal) => { + exited = true; + if (stdoutRemainder) processLine(stdoutRemainder); + if (stderrRemainder) processLine(stderrRemainder); + resolve({ code, exitSignal }); + }); + }); + + if (signal.aborted) { + report({ type: "closed", reason: "aborted" }); + return; + } + + if (result.spawnError) { + if (isNotFoundError(result.spawnError)) { + throw new Error( + `${config.binary} is not installed or not on PATH. Install cloudflared and retry.`, + ); + } + throw new Error(redactSecret(result.spawnError.message, config.tunnelToken)); + } + + if (!readyReported) { + const detail = lastOutputLine ? `: ${lastOutputLine}` : ""; + throw new Error( + `cloudflared exited before tunnel became ready (code ${result.code ?? "null"})${detail}`, + ); + } + + if (result.code && result.code !== 0) { + const detail = lastOutputLine ? `: ${lastOutputLine}` : ""; + const message = `cloudflared exited with code ${result.code}${detail}`; + report({ type: "error", message, recoverable: false }); + throw new Error(message); + } + + report({ type: "closed" }); + } finally { + signal.removeEventListener("abort", onAbort); + if (forceKillTimer) clearTimeout(forceKillTimer); + } + }, + }; +} diff --git a/plugins/cloudflared-tunnel/shared/settings.ts b/plugins/cloudflared-tunnel/shared/settings.ts new file mode 100644 index 0000000000..382b63ce9a --- /dev/null +++ b/plugins/cloudflared-tunnel/shared/settings.ts @@ -0,0 +1,17 @@ +import { defineSettings } from "@getpaseo/plugin"; +import { z } from "zod"; + +export const cloudflaredSettings = defineSettings({ + id: "cloudflared", + scope: "host", + version: 1, + schema: z.object({ + binaryPath: z.string().trim().min(1).optional(), + /** Cloudflare named tunnel token (passed via TUNNEL_TOKEN). Runs the remotely configured tunnel. */ + tunnelToken: z.string().trim().min(1).optional(), + /** Public base URL routed to the named tunnel in Cloudflare Zero Trust. */ + publicBaseUrl: z.string().trim().min(1).optional(), + }), +}); + +export type CloudflaredSettings = z.infer; diff --git a/plugins/cloudflared-tunnel/test/cloudflared.test.ts b/plugins/cloudflared-tunnel/test/cloudflared.test.ts new file mode 100644 index 0000000000..d44b785fed --- /dev/null +++ b/plugins/cloudflared-tunnel/test/cloudflared.test.ts @@ -0,0 +1,260 @@ +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { TunnelEvent } from "@getpaseo/plugin/server"; +import { afterEach, describe, expect, it } from "vitest"; +import { createCloudflaredTunnelProvider } from "../server/cloudflared.js"; + +const tempDirs: string[] = []; + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +async function createFakeCloudflared(scriptBody: string): Promise<{ dir: string; binary: string }> { + const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-fake-cloudflared-")); + tempDirs.push(dir); + const binary = path.join(dir, "cloudflared"); + await writeFile(binary, `#!${process.execPath}\n${scriptBody}\n`, "utf8"); + await chmod(binary, 0o755); + return { dir, binary }; +} + +const unusedPaseo = {} as never; + +describe("cloudflared-tunnel built-in plugin", () => { + it("reports unavailable with install guidance when cloudflared is missing", async () => { + const emptyDir = await mkdtemp(path.join(os.tmpdir(), "paseo-empty-path-")); + tempDirs.push(emptyDir); + const provider = createCloudflaredTunnelProvider({ + env: { ...process.env, PATH: emptyDir }, + }); + + const status = await provider.status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }); + expect(status).toMatchObject({ + status: "unavailable", + installUrl: expect.stringContaining("cloudflare.com"), + fixHint: expect.stringContaining("cloudflared"), + }); + }); + + it("opens a quick tunnel, parses trycloudflare.com URL as ephemeral, and terminates on abort", async () => { + const markerFile = path.join(os.tmpdir(), `paseo-cf-term-${Date.now()}-${Math.random()}.txt`); + const { dir } = await createFakeCloudflared(` +const fs = require("node:fs"); +const args = process.argv.slice(2); +if (args[0] === "--version") { + console.log("cloudflared version 2026.5.0 (built 2026-05-01)"); + process.exit(0); +} +fs.writeFileSync(${JSON.stringify(markerFile)}, "started:" + args.join(" ")); +console.error("INF +------------------------------------------------------------+"); +console.error("INF | https://quick-demo-123.trycloudflare.com |"); +console.error("INF +------------------------------------------------------------+"); +process.on("SIGTERM", () => { + fs.writeFileSync(${JSON.stringify(markerFile)}, "terminated"); + process.exit(0); +}); +setInterval(() => {}, 10_000); +`); + tempDirs.push(markerFile); + + const provider = createCloudflaredTunnelProvider({ + env: { ...process.env, PATH: `${dir}${path.delimiter}${process.env.PATH ?? ""}` }, + }); + + const status = await provider.status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }); + expect(status).toEqual({ + status: "available", + detail: "cloudflared version 2026.5.0 (built 2026-05-01) (quick tunnel)", + }); + + const controller = new AbortController(); + const events: TunnelEvent[] = []; + let readyResolve!: () => void; + const readyPromise = new Promise((resolve) => { + readyResolve = resolve; + }); + + const running = provider.open( + { id: "tun_1", host: "127.0.0.1", port: 4321, label: "External MCP" }, + { + paseo: unusedPaseo, + signal: controller.signal, + report(event) { + events.push(event); + if (event.type === "ready") readyResolve(); + }, + }, + ); + + await readyPromise; + expect(await readFile(markerFile, "utf8")).toBe( + "started:tunnel --no-autoupdate --url http://127.0.0.1:4321", + ); + + controller.abort(); + await running; + + expect(await readFile(markerFile, "utf8")).toBe("terminated"); + expect(events).toEqual([ + { type: "connecting" }, + { + type: "ready", + url: "https://quick-demo-123.trycloudflare.com", + stability: "ephemeral", + }, + { type: "closed", reason: "aborted" }, + ]); + }); + + it("supports named tunnels via TUNNEL_TOKEN env without --url, reports stable URL, and redacts token on failure", async () => { + const captureFile = path.join(os.tmpdir(), `paseo-cf-named-${Date.now()}-${Math.random()}.txt`); + const { binary } = await createFakeCloudflared(` +const fs = require("node:fs"); +const args = process.argv.slice(2); +if (args[0] === "--version") { + console.log("cloudflared version 2026.5.0"); + process.exit(0); +} +fs.writeFileSync(${JSON.stringify(captureFile)}, JSON.stringify({ + args, + token: process.env.TUNNEL_TOKEN ?? null, +})); +if (process.env.TUNNEL_TOKEN === "bad-secret-token") { + console.error("ERR invalid token bad-secret-token"); + process.exit(1); +} +console.error("INF Registered tunnel connection connIndex=0"); +process.on("SIGTERM", () => process.exit(0)); +setInterval(() => {}, 10_000); +`); + tempDirs.push(captureFile); + + const provider = createCloudflaredTunnelProvider({ + readSettings: async () => ({ + binaryPath: binary, + tunnelToken: "secret-named-token", + publicBaseUrl: "https://mcp.example.com/", + }), + }); + + const controller = new AbortController(); + const events: TunnelEvent[] = []; + let readyResolve!: () => void; + const readyPromise = new Promise((resolve) => { + readyResolve = resolve; + }); + + const running = provider.open( + { id: "tun_2", host: "127.0.0.1", port: 9000 }, + { + paseo: unusedPaseo, + signal: controller.signal, + report(event) { + events.push(event); + if (event.type === "ready") readyResolve(); + }, + }, + ); + + await readyPromise; + expect(JSON.parse(await readFile(captureFile, "utf8"))).toEqual({ + args: ["tunnel", "--no-autoupdate", "run"], + token: "secret-named-token", + }); + + controller.abort(); + await running; + + expect(events).toEqual([ + { type: "connecting" }, + { type: "ready", url: "https://mcp.example.com", stability: "stable" }, + { type: "closed", reason: "aborted" }, + ]); + + // Redacts token if named tunnel exits with an error containing the token + const failingProvider = createCloudflaredTunnelProvider({ + readSettings: async () => ({ + binaryPath: binary, + tunnelToken: "bad-secret-token", + publicBaseUrl: "https://mcp.example.com", + }), + }); + await expect( + failingProvider.open( + { id: "tun_3", host: "127.0.0.1", port: 9000 }, + { + paseo: unusedPaseo, + signal: new AbortController().signal, + report() {}, + }, + ), + ).rejects.toThrow(/\[REDACTED\]/); + }); + + it("brackets IPv6 hosts when launching quick tunnels", async () => { + const argsFile = path.join(os.tmpdir(), `paseo-cf-v6-${Date.now()}-${Math.random()}.txt`); + const { binary } = await createFakeCloudflared(` +const fs = require("node:fs"); +const args = process.argv.slice(2); +fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(args)); +console.error("INF https://ipv6-demo.trycloudflare.com"); +process.on("SIGTERM", () => process.exit(0)); +setInterval(() => {}, 10_000); +`); + tempDirs.push(argsFile); + + const provider = createCloudflaredTunnelProvider({ + readSettings: async () => ({ binaryPath: binary }), + }); + const controller = new AbortController(); + let readyResolve!: () => void; + const readyPromise = new Promise((resolve) => { + readyResolve = resolve; + }); + + const running = provider.open( + { id: "tun_v6", host: "::1", port: 4321 }, + { + paseo: unusedPaseo, + signal: controller.signal, + report(event) { + if (event.type === "ready") readyResolve(); + }, + }, + ); + + await readyPromise; + expect(JSON.parse(await readFile(argsFile, "utf8"))).toEqual([ + "tunnel", + "--no-autoupdate", + "--url", + "http://[::1]:4321", + ]); + + controller.abort(); + await running; + }); + + it("reports configuration error when tunnelToken is set without publicBaseUrl", async () => { + const provider = createCloudflaredTunnelProvider({ + readSettings: async () => ({ tunnelToken: "only-token" }), + }); + + const status = await provider.status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }); + expect(status).toMatchObject({ + status: "unavailable", + reason: expect.stringContaining("publicBaseUrl"), + }); + }); +}); diff --git a/plugins/tailscale-funnel/index.server.ts b/plugins/tailscale-funnel/index.server.ts new file mode 100644 index 0000000000..79ebf936e7 --- /dev/null +++ b/plugins/tailscale-funnel/index.server.ts @@ -0,0 +1,6 @@ +import type { PluginServerContext } from "@getpaseo/plugin/server"; +import { createTailscaleFunnelProvider } from "./server/tailscale.js"; + +export default function contribute(server: PluginServerContext) { + return server.registerTunnelProvider(createTailscaleFunnelProvider()); +} diff --git a/plugins/tailscale-funnel/paseo-plugin.json b/plugins/tailscale-funnel/paseo-plugin.json new file mode 100644 index 0000000000..c47bb2ab7a --- /dev/null +++ b/plugins/tailscale-funnel/paseo-plugin.json @@ -0,0 +1 @@ +{ "id": "tailscale-funnel", "requirements": { "paseo": ">=0.17.6" } } diff --git a/plugins/tailscale-funnel/server/tailscale.ts b/plugins/tailscale-funnel/server/tailscale.ts new file mode 100644 index 0000000000..be48b9a693 --- /dev/null +++ b/plugins/tailscale-funnel/server/tailscale.ts @@ -0,0 +1,344 @@ +import { + execCommand, + type TunnelProviderRegistration, + type TunnelProviderStatus, +} from "@getpaseo/plugin/server"; + +export const TAILSCALE_FUNNEL_PORTS = [443, 8443, 10000] as const; + +const TAILSCALE_INSTALL_URL = "https://tailscale.com/download"; +const TAILSCALE_FUNNEL_DOCS_URL = "https://tailscale.com/kb/1223/funnel"; + +export interface TailscaleFunnelProviderOptions { + binary?: string; + env?: NodeJS.ProcessEnv; +} + +interface TailscaleStatusJson { + BackendState?: unknown; + Self?: { + DNSName?: unknown; + Capabilities?: unknown; + CapMap?: unknown; + }; +} + +interface TailscaleFunnelStatusJson { + TCP?: Record; + Web?: Record; + AllowFunnel?: Record; +} + +function formatHostForUrl(host: string): string { + return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; +} + +function isNotFoundError(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error.code === "ENOENT" || error.code === "ENOTDIR") + ); +} + +function hasFunnelCapability(self: NonNullable): boolean { + if (Array.isArray(self.Capabilities)) { + if ( + self.Capabilities.some( + (capability) => typeof capability === "string" && /funnel/i.test(capability), + ) + ) { + return true; + } + } + if (self.CapMap && typeof self.CapMap === "object" && !Array.isArray(self.CapMap)) { + for (const [key, value] of Object.entries(self.CapMap)) { + if (/funnel/i.test(key) && value !== false && value !== null && value !== undefined) { + return true; + } + } + } + return false; +} + +function parsePortFromKey(key: string): number | null { + const direct = /^\d+$/.exec(key.trim()); + if (direct) { + const value = Number(direct[0]); + return Number.isInteger(value) ? value : null; + } + const hostPort = /:(\d+)$/.exec(key.trim()); + if (hostPort) { + const value = Number(hostPort[1]); + return Number.isInteger(value) ? value : null; + } + return null; +} + +export function extractOccupiedFunnelPorts(raw: unknown): Set { + const occupied = new Set(); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return occupied; + const status = raw as TailscaleFunnelStatusJson; + + if (status.TCP && typeof status.TCP === "object") { + for (const key of Object.keys(status.TCP)) { + const port = parsePortFromKey(key); + if (port !== null) occupied.add(port); + } + } + if (status.Web && typeof status.Web === "object") { + for (const key of Object.keys(status.Web)) { + const port = parsePortFromKey(key); + if (port !== null) occupied.add(port); + } + } + if (status.AllowFunnel && typeof status.AllowFunnel === "object") { + for (const [key, enabled] of Object.entries(status.AllowFunnel)) { + if (!enabled) continue; + const port = parsePortFromKey(key); + if (port !== null) occupied.add(port); + } + } + return occupied; +} + +function waitForAbort(signal: AbortSignal): Promise { + if (signal.aborted) return Promise.resolve(); + return new Promise((resolve) => { + signal.addEventListener("abort", () => resolve(), { once: true }); + }); +} + +export function createTailscaleFunnelProvider( + options: TailscaleFunnelProviderOptions = {}, +): TunnelProviderRegistration { + const binary = options.binary ?? "tailscale"; + const env = options.env; + const allocatedPorts = new Set(); + let allocationTail: Promise = Promise.resolve(); + + async function withAllocationLock(run: () => Promise): Promise { + const previous = allocationTail; + let release!: () => void; + allocationTail = new Promise((resolve) => { + release = resolve; + }); + await previous; + try { + return await run(); + } finally { + release(); + } + } + + async function probeStatus( + signal?: AbortSignal, + ): Promise< + | { ok: true; dnsName: string; status: TunnelProviderStatus } + | { ok: false; status: Extract } + > { + let stdout: string; + try { + ({ stdout } = await execCommand(binary, ["status", "--json"], { + env, + signal, + timeout: 5_000, + })); + } catch (error) { + if (isNotFoundError(error)) { + return { + ok: false, + status: { + status: "unavailable", + reason: `${binary} CLI is not installed or not on PATH.`, + installUrl: TAILSCALE_INSTALL_URL, + fixHint: "Install Tailscale and make sure the tailscale CLI is on PATH.", + }, + }; + } + return { + ok: false, + status: { + status: "unavailable", + reason: `Tailscale is not running or could not be queried: ${error instanceof Error ? error.message : String(error)}`, + fixHint: "Start Tailscale and run `tailscale status` to verify connectivity.", + }, + }; + } + + let parsed: TailscaleStatusJson; + try { + parsed = JSON.parse(stdout) as TailscaleStatusJson; + } catch { + return { + ok: false, + status: { + status: "unavailable", + reason: "Could not parse output from `tailscale status --json`.", + fixHint: "Verify that your Tailscale CLI is up to date.", + }, + }; + } + + const backendState = typeof parsed.BackendState === "string" ? parsed.BackendState : "unknown"; + if (backendState !== "Running") { + return { + ok: false, + status: { + status: "unavailable", + reason: `Tailscale is not connected (state: ${backendState}).`, + fixHint: "Run `tailscale up` and sign in to your tailnet.", + }, + }; + } + + const self = parsed.Self; + const dnsName = + typeof self?.DNSName === "string" ? self.DNSName.trim().replace(/\.+$/, "") : ""; + if (!dnsName) { + return { + ok: false, + status: { + status: "unavailable", + reason: "MagicDNS is not enabled for this Tailscale node.", + fixHint: "Enable MagicDNS in the Tailscale admin console.", + }, + }; + } + + if (!self || !hasFunnelCapability(self)) { + return { + ok: false, + status: { + status: "unavailable", + reason: "Tailscale Funnel is not enabled for this node or tailnet.", + installUrl: TAILSCALE_FUNNEL_DOCS_URL, + fixHint: + "Enable HTTPS certificates and Funnel in your Tailscale admin console and ACL policy.", + }, + }; + } + + return { + ok: true, + dnsName, + status: { + status: "available", + detail: dnsName, + }, + }; + } + + async function inspectOccupiedPorts(signal?: AbortSignal): Promise> { + try { + const { stdout } = await execCommand(binary, ["funnel", "status", "--json"], { + env, + signal, + timeout: 5_000, + }); + const trimmed = stdout.trim(); + if (!trimmed) return new Set(); + return extractOccupiedFunnelPorts(JSON.parse(trimmed)); + } catch { + return new Set(); + } + } + + async function disableFunnelPort(port: number): Promise { + await withAllocationLock(async () => { + try { + await execCommand(binary, ["funnel", `--https=${port}`, "off"], { + env, + timeout: 10_000, + }); + } catch { + // Best-effort cleanup so teardown completes even if Tailscale stopped. + } finally { + allocatedPorts.delete(port); + } + }); + } + + return { + id: "tailscale-funnel", + label: "Tailscale Funnel", + description: "Expose local HTTP endpoints on your Tailscale MagicDNS hostname via Funnel.", + docsUrl: TAILSCALE_FUNNEL_DOCS_URL, + + async status({ signal }): Promise { + const probe = await probeStatus(signal); + return probe.status; + }, + + async open(target, { report, signal }): Promise { + report({ type: "connecting" }); + + const probe = await probeStatus(signal); + if (!probe.ok) { + throw new Error(probe.status.reason); + } + + const targetUrl = `http://${formatHostForUrl(target.host)}:${target.port}`; + let assignedPort: number | null = null; + + await withAllocationLock(async () => { + if (signal.aborted) return; + const occupied = await inspectOccupiedPorts(signal); + const freePort = TAILSCALE_FUNNEL_PORTS.find( + (candidate) => !occupied.has(candidate) && !allocatedPorts.has(candidate), + ); + if (freePort === undefined) { + throw new Error( + "All 3 Tailscale Funnel HTTPS ports (443, 8443, 10000) are already in use. Close an existing Funnel exposure before opening another.", + ); + } + allocatedPorts.add(freePort); + try { + await execCommand(binary, ["funnel", "--bg", `--https=${freePort}`, targetUrl], { + env, + signal, + timeout: 15_000, + }); + assignedPort = freePort; + } catch (error) { + allocatedPorts.delete(freePort); + throw new Error( + `Failed to start Tailscale Funnel on HTTPS port ${freePort}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } + }); + + if (assignedPort === null) { + report({ type: "closed", reason: "aborted" }); + return; + } + + const activePort = assignedPort; + try { + if (signal.aborted) { + await disableFunnelPort(activePort); + report({ type: "closed", reason: "aborted" }); + return; + } + + const publicUrl = + activePort === 443 + ? `https://${probe.dnsName}` + : `https://${probe.dnsName}:${activePort}`; + report({ + type: "ready", + url: publicUrl, + stability: "stable", + }); + + await waitForAbort(signal); + await disableFunnelPort(activePort); + report({ type: "closed", reason: "aborted" }); + } finally { + allocatedPorts.delete(activePort); + } + }, + }; +} diff --git a/plugins/tailscale-funnel/test/tailscale.test.ts b/plugins/tailscale-funnel/test/tailscale.test.ts new file mode 100644 index 0000000000..138b7d9fe5 --- /dev/null +++ b/plugins/tailscale-funnel/test/tailscale.test.ts @@ -0,0 +1,251 @@ +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { TunnelEvent } from "@getpaseo/plugin/server"; +import { afterEach, describe, expect, it } from "vitest"; +import { createTailscaleFunnelProvider } from "../server/tailscale.js"; + +const tempDirs: string[] = []; + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +interface FakeTailscaleState { + statusJson: Record; + funnelPorts: Record; + history: string[][]; +} + +async function createFakeTailscale(initial: { + statusJson: Record; + funnelPorts?: Record; +}): Promise<{ binary: string; stateFile: string; readState: () => Promise }> { + const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-fake-tailscale-")); + tempDirs.push(dir); + const stateFile = path.join(dir, "state.json"); + const initialState: FakeTailscaleState = { + statusJson: initial.statusJson, + funnelPorts: initial.funnelPorts ?? {}, + history: [], + }; + await writeFile(stateFile, JSON.stringify(initialState, null, 2), "utf8"); + + const binary = path.join(dir, "tailscale"); + await writeFile( + binary, + `#!${process.execPath} +const fs = require("node:fs"); +const stateFile = ${JSON.stringify(stateFile)}; +const args = process.argv.slice(2); +const state = JSON.parse(fs.readFileSync(stateFile, "utf8")); +state.history.push(args); + +if (args[0] === "status" && args[1] === "--json") { + fs.writeFileSync(stateFile, JSON.stringify(state, null, 2)); + console.log(JSON.stringify(state.statusJson)); + process.exit(0); +} + +if (args[0] === "funnel" && args[1] === "status" && args[2] === "--json") { + fs.writeFileSync(stateFile, JSON.stringify(state, null, 2)); + const tcp = {}; + for (const port of Object.keys(state.funnelPorts)) { + tcp[port] = { HTTPS: true }; + } + console.log(JSON.stringify({ TCP: tcp })); + process.exit(0); +} + +if (args[0] === "funnel" && args[1] === "--bg") { + const httpsArg = args.find((a) => a.startsWith("--https=")); + const port = httpsArg ? httpsArg.slice("--https=".length) : "443"; + const target = args[args.length - 1]; + state.funnelPorts[port] = target; + fs.writeFileSync(stateFile, JSON.stringify(state, null, 2)); + process.exit(0); +} + +if (args[0] === "funnel" && args[args.length - 1] === "off") { + const httpsArg = args.find((a) => a.startsWith("--https=")); + const port = httpsArg ? httpsArg.slice("--https=".length) : "443"; + delete state.funnelPorts[port]; + fs.writeFileSync(stateFile, JSON.stringify(state, null, 2)); + process.exit(0); +} + +console.error("Unexpected tailscale args:", args.join(" ")); +process.exit(1); +`, + "utf8", + ); + await chmod(binary, 0o755); + + return { + binary, + stateFile, + readState: async () => JSON.parse(await readFile(stateFile, "utf8")) as FakeTailscaleState, + }; +} + +const unusedPaseo = {} as never; + +describe("tailscale-funnel built-in plugin", () => { + it("reports unavailable when tailscale CLI is missing", async () => { + const emptyDir = await mkdtemp(path.join(os.tmpdir(), "paseo-empty-ts-path-")); + tempDirs.push(emptyDir); + const provider = createTailscaleFunnelProvider({ + env: { ...process.env, PATH: emptyDir }, + }); + + const status = await provider.status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }); + expect(status).toMatchObject({ + status: "unavailable", + installUrl: "https://tailscale.com/download", + }); + }); + + it("reports clear diagnostics when logged out, MagicDNS is off, or Funnel is disabled", async () => { + const loggedOut = await createFakeTailscale({ + statusJson: { BackendState: "NeedsLogin", Self: {} }, + }); + expect( + await createTailscaleFunnelProvider({ binary: loggedOut.binary }).status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }), + ).toMatchObject({ + status: "unavailable", + reason: expect.stringContaining("NeedsLogin"), + }); + + const noMagicDns = await createFakeTailscale({ + statusJson: { BackendState: "Running", Self: { DNSName: "" } }, + }); + expect( + await createTailscaleFunnelProvider({ binary: noMagicDns.binary }).status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }), + ).toMatchObject({ + status: "unavailable", + reason: expect.stringContaining("MagicDNS"), + }); + + const noFunnel = await createFakeTailscale({ + statusJson: { + BackendState: "Running", + Self: { DNSName: "devbox.tailnet.ts.net.", Capabilities: [] }, + }, + }); + expect( + await createTailscaleFunnelProvider({ binary: noFunnel.binary }).status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }), + ).toMatchObject({ + status: "unavailable", + reason: expect.stringContaining("Funnel"), + }); + }); + + it("allocates ports 443, 8443, 10000, rejects a 4th exposure, and turns off ports on abort", async () => { + const fake = await createFakeTailscale({ + statusJson: { + BackendState: "Running", + Self: { + DNSName: "devbox.tailnet.ts.net.", + Capabilities: ["https://tailscale.com/cap/funnel-v1"], + }, + }, + }); + + const provider = createTailscaleFunnelProvider({ binary: fake.binary }); + expect( + await provider.status({ + paseo: unusedPaseo, + signal: new AbortController().signal, + }), + ).toEqual({ + status: "available", + detail: "devbox.tailnet.ts.net", + }); + + const openExposure = async (id: string, port: number, host = "127.0.0.1") => { + const controller = new AbortController(); + const events: TunnelEvent[] = []; + let resolveReady!: (url: string) => void; + const ready = new Promise((resolve) => { + resolveReady = resolve; + }); + const done = provider.open( + { id, host, port }, + { + paseo: unusedPaseo, + signal: controller.signal, + report(event) { + events.push(event); + if (event.type === "ready") resolveReady(event.url); + }, + }, + ); + const url = await ready; + return { controller, events, url, done }; + }; + + const first = await openExposure("e1", 3001); + const second = await openExposure("e2", 3002); + const third = await openExposure("e3", 3003); + + expect(first.url).toBe("https://devbox.tailnet.ts.net"); + expect(second.url).toBe("https://devbox.tailnet.ts.net:8443"); + expect(third.url).toBe("https://devbox.tailnet.ts.net:10000"); + expect(first.events).toEqual([ + { type: "connecting" }, + { type: "ready", url: "https://devbox.tailnet.ts.net", stability: "stable" }, + ]); + + // 4th exposure fails cleanly because all 3 Funnel ports are in use. + await expect( + provider.open( + { id: "e4", host: "127.0.0.1", port: 3004 }, + { + paseo: unusedPaseo, + signal: new AbortController().signal, + report() {}, + }, + ), + ).rejects.toThrow(/All 3 Tailscale Funnel HTTPS ports \(443, 8443, 10000\) are already in use/); + + // Abort the second exposure (port 8443) -> runs `tailscale funnel --https=8443 off` and frees port 8443. + second.controller.abort(); + await second.done; + expect(second.events.at(-1)).toEqual({ type: "closed", reason: "aborted" }); + + const stateAfterClose = await fake.readState(); + expect(stateAfterClose.funnelPorts).toEqual({ + "443": "http://127.0.0.1:3001", + "10000": "http://127.0.0.1:3003", + }); + + // A new exposure reuses the freed port 8443 and brackets IPv6 hosts. + const fourth = await openExposure("e4", 3004, "::1"); + expect(fourth.url).toBe("https://devbox.tailnet.ts.net:8443"); + const stateWithIpv6 = await fake.readState(); + expect(stateWithIpv6.funnelPorts["8443"]).toBe("http://[::1]:3004"); + + first.controller.abort(); + third.controller.abort(); + fourth.controller.abort(); + await Promise.all([first.done, third.done, fourth.done]); + + const finalState = await fake.readState(); + expect(finalState.funnelPorts).toEqual({}); + expect(finalState.history).toContainEqual(["funnel", "--https=443", "off"]); + expect(finalState.history).toContainEqual(["funnel", "--https=8443", "off"]); + expect(finalState.history).toContainEqual(["funnel", "--https=10000", "off"]); + }); +}); diff --git a/public-docs/plugins/reference.md b/public-docs/plugins/reference.md index 50c1895e7a..33cd756dbe 100644 --- a/public-docs/plugins/reference.md +++ b/public-docs/plugins/reference.md @@ -864,6 +864,90 @@ export default function contribute(server: PluginServerContext) { See the complete [worktrunk example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk). +## Tunnel providers {#tunnel-providers} + +**Requires Paseo 0.18.** Register a tunnel provider from `index.server.ts` with +`server.registerTunnelProvider()` to turn a local HTTP `host:port` target into a public HTTPS URL. +The registration returns a cleanup function that unregisters the provider and closes its active +exposures. + +```ts +import { + execCommand, + spawnProcess, + terminateProcess, + type PluginServerContext, +} from "@getpaseo/plugin/server"; + +export default function contribute(server: PluginServerContext) { + return server.registerTunnelProvider({ + id: "custom-tunnel", + label: "Custom Tunnel", + description: "Expose local HTTP targets through a custom tunnel binary.", + docsUrl: "https://example.com/docs/custom-tunnel", + async status({ signal }) { + try { + const { stdout } = await execCommand("custom-tunnel", ["--version"], { + signal, + timeout: 5_000, + }); + return { status: "available", detail: stdout.trim() || undefined }; + } catch { + return { + status: "unavailable", + reason: "custom-tunnel is not installed or not on PATH.", + installUrl: "https://example.com/install", + fixHint: "Install custom-tunnel and make sure that it is on PATH.", + }; + } + }, + async open(target, { report, signal }) { + report({ type: "connecting" }); + const child = spawnProcess("custom-tunnel", ["http", `${target.host}:${target.port}`], { + stdio: "pipe", + }); + signal.addEventListener( + "abort", + () => { + void terminateProcess(child, "SIGTERM").catch(() => undefined); + }, + { once: true }, + ); + let ready = false; + child.stderr.on("data", (chunk) => { + if (ready || signal.aborted) return; + const match = /https:\/\/[a-z0-9.-]+/i.exec(String(chunk)); + if (!match) return; + ready = true; + report({ type: "ready", url: match[0], stability: "ephemeral" }); + }); + await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("close", () => resolve()); + }); + report({ type: "closed", reason: signal.aborted ? "aborted" : undefined }); + }, + }); +} +``` + +- `id` must match `/^[a-z][a-z0-9._-]*$/` and must be unique across installed and built-in plugins. +- `status({ paseo, signal })` checks whether the provider can open tunnels on this host. Return + `{ status: "available", detail? }` or `{ status: "unavailable", reason, installUrl?, fixHint? }`. +- `open(target, { paseo, signal, report })` owns one exposure until `signal` aborts or the tunnel + closes. `target` carries `{ id, host, port, label?, slug? }`. +- Call `report(event)` as the exposure changes state: + - `{ type: "connecting", detail? }` + - `{ type: "ready", url, stability?: "ephemeral" | "stable", detail? }` + - `{ type: "reconnecting", reason? }` + - `{ type: "error", message, recoverable?: boolean }` + - `{ type: "closed", reason? }` +- Keep `open()` pending while the tunnel stays up. When `signal` aborts, stop child processes or + remote rules, report `{ type: "closed" }`, and resolve. If `open()` throws or exits before + reporting `ready`, Paseo fails the exposure and removes it cleanly. + +See the complete [tunnel-provider example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/tunnel-provider). + ## Entry point and cleanup Each present entry default-exports one contribution function and returns cleanup. Client entries