Epic: grand tunnel restructuring and CLI UX (#640)

* feat: restructure tunnel handling around provider-based service model" -m "Introduce tunnel service/registry/provider architecture and move Cloudflare handling behind provider adapter." -m "Add canonical tunnel modes (quick, managed-remote, managed-local) with legacy named/try-cf-tunnel compatibility mapping." -m "Add managed-local config-path support, normalized API response fields, tunnel-focused tests, and shell aliases for tunnel test workflows.

* feat(tunnels): harden managed startup and decouple runtime APIs

Improve managed Cloudflare startup reliability with explicit config validation, YAML diagnostics, and readiness detection based on process output instead of fixed delay assumptions.

Refactor server tunnel lifecycle around provider-aware runtime state and API responses while keeping legacy Cloudflare token endpoint compatibility, and add coverage for unsupported mode validation plus managed-local startup cases.

* feat: remove named tunnel mode and standardize managed modes

Replace named tunnel terminology with managed-remote and managed-local across API, server state, and UI settings without legacy aliases.

Add provider capability discovery endpoint and descriptor-based mode validation, including explicit mode_unsupported errors for removed mode values.

* feat(tunnels): finalize provider-aware tunnel UX and managed-local safety

Restructure tunnel settings with provider selection, mode chips, persisted managed-local config path, and clearer session badges while preserving existing tunnel flows.

Add legacy named-data migration, provider discovery CLI, and user-friendly managed-local config validation/error messaging with updated API/CLI/server tests.

* Add provider icon to tunnel settings

* Add control+C to stop tunnel

* feat(cli): add tunnel lifecycle profiles and preserve preset naming

Replace legacy tunnel flags with explicit tunnel lifecycle commands, daemon-by-default startup, and file-backed log tailing so tunnel operations are predictable and provider-agnostic.

Add managed-remote profile storage/migration for start-by-name workflows and propagate preset summaries to settings so user-defined profile names are preserved instead of falling back to Default.

* feat: improve tunnel CLI safety and startup UX

Add interactive TTL support and per-start TTL overrides for tunnel start
Strengthen port safety and instance validation with clearer startup and error guidance
Refine tunnel doctor and CLI output formatting for clearer, less noisy diagnostics

* feat: add TTL support, safety gates, and polished tunnel CLI output

* fix: harden tunnel doctor checks and CLI port handling

* fix: improve tunnel CLI diagnostics and profile output

* fix: streamline tunnel profile UX and doctor diagnostics

* fix: clarify tunnel replacement behavior across CLI and UI

* Upd docs

* docs: add mandatory clack CLI skill guidance. cleanup

* fix: standardize tunnel CLI mode parity and prompt UX

* fix: align CLI quiet and JSON output behavior

* feat/web-serve: in-progress animation

* fix: tunnel doctor managed remote validation

* Fix: security tightening

* fix: instance restart ux

* fix: tighten tunnel doctor input handling and CLI port/prompt validation

* chore: remove tunnel test suites per owner request

---------

Signed-off-by: Iuliia Ivashko <yulia.ivashko@gmail.com>
This commit is contained in:
Iuliia Ivashko
2026-03-12 19:40:22 +02:00
committed by GitHub
parent 77467311f1
commit 63f1698cdd
20 changed files with 7360 additions and 1277 deletions
+166
View File
@@ -0,0 +1,166 @@
import {
TUNNEL_MODE_QUICK,
TUNNEL_PROVIDER_CLOUDFLARE,
TunnelServiceError,
normalizeTunnelStartRequest,
validateTunnelStartRequest,
} from './types.js';
export function createTunnelService({
registry,
getController,
setController,
getActivePort,
onQuickTunnelWarning,
}) {
if (!registry) {
throw new Error('Tunnel service requires a provider registry');
}
const resolveActiveMode = () => {
const controller = getController();
if (!controller || typeof controller.mode !== 'string') {
return null;
}
return controller.mode;
};
const resolveActiveProvider = () => {
const controller = getController();
if (!controller || typeof controller.provider !== 'string') {
return null;
}
return controller.provider;
};
const stop = () => {
const controller = getController();
if (!controller) {
return false;
}
const providerId = typeof controller.provider === 'string' ? controller.provider : '';
const provider = providerId ? registry.get(providerId) : null;
if (provider?.stop) {
provider.stop(controller);
} else {
controller.stop?.();
}
setController(null);
return true;
};
const checkAvailability = async (providerId) => {
const provider = registry.get(providerId);
if (!provider) {
throw new TunnelServiceError('provider_unsupported', `Unsupported tunnel provider: ${providerId}`);
}
const result = await provider.checkAvailability();
return result;
};
// Mutex to prevent concurrent tunnel starts from orphaning child processes.
let startLock = Promise.resolve();
const start = async (rawRequest, options = {}) => {
let releaseLock;
const lockPromise = new Promise((resolve) => { releaseLock = resolve; });
const previousLock = startLock;
startLock = lockPromise;
await previousLock;
try {
const request = normalizeTunnelStartRequest(rawRequest);
const provider = registry.get(request.provider);
if (!provider) {
throw new TunnelServiceError('provider_unsupported', `Unsupported tunnel provider: ${request.provider}`);
}
validateTunnelStartRequest(request, provider.capabilities);
let publicUrl = provider.resolvePublicUrl(getController());
const activeMode = resolveActiveMode();
if (publicUrl && activeMode !== request.mode) {
stop();
publicUrl = null;
}
if (!publicUrl) {
const availability = await provider.checkAvailability();
if (!availability?.available) {
const missingDependencyMessage = typeof availability?.message === 'string' && availability.message.trim().length > 0
? availability.message
: (request.provider === TUNNEL_PROVIDER_CLOUDFLARE
? 'cloudflared is not installed. Install it with: brew install cloudflared'
: `Required dependency for provider '${request.provider}' is missing`);
throw new TunnelServiceError('missing_dependency', missingDependencyMessage);
}
const activePort = Number.isFinite(getActivePort?.()) ? getActivePort() : null;
const originUrl = activePort !== null ? `http://127.0.0.1:${activePort}` : undefined;
const controller = await provider.start(request, {
activePort,
originUrl,
...options,
});
controller.provider = request.provider;
setController(controller);
publicUrl = provider.resolvePublicUrl(controller);
if (!publicUrl) {
stop();
throw new TunnelServiceError('startup_failed', 'Tunnel started but no public URL was assigned');
}
if (request.mode === TUNNEL_MODE_QUICK) {
onQuickTunnelWarning?.();
}
}
return {
publicUrl,
request,
activeMode: request.mode,
provider: request.provider,
providerMetadata: provider.getMetadata?.(getController()) ?? null,
};
} finally {
releaseLock();
}
};
const getPublicUrl = () => {
const controller = getController();
if (!controller) {
return null;
}
const provider = registry.get(controller.provider);
if (!provider) {
return controller.getPublicUrl?.() ?? null;
}
return provider.resolvePublicUrl(controller);
};
const getProviderMetadata = () => {
const controller = getController();
if (!controller) {
return null;
}
const provider = registry.get(controller.provider);
return provider?.getMetadata?.(controller) ?? null;
};
return {
start,
stop,
checkAvailability,
getPublicUrl,
getProviderMetadata,
resolveActiveMode,
resolveActiveProvider,
};
}
@@ -0,0 +1,260 @@
import {
checkCloudflareApiReachability,
checkCloudflaredAvailable,
inspectManagedLocalCloudflareConfig,
normalizeCloudflareTunnelHostname,
startCloudflareManagedLocalTunnel,
startCloudflareManagedRemoteTunnel,
startCloudflareQuickTunnel,
} from '../../cloudflare-tunnel.js';
import {
TUNNEL_INTENT_EPHEMERAL_PUBLIC,
TUNNEL_INTENT_PERSISTENT_PUBLIC,
TUNNEL_MODE_MANAGED_LOCAL,
TUNNEL_MODE_MANAGED_REMOTE,
TUNNEL_MODE_QUICK,
TUNNEL_PROVIDER_CLOUDFLARE,
TunnelServiceError,
} from '../types.js';
export const cloudflareTunnelProviderCapabilities = {
provider: TUNNEL_PROVIDER_CLOUDFLARE,
defaults: {
mode: TUNNEL_MODE_QUICK,
optionDefaults: {},
},
modes: [
{
key: TUNNEL_MODE_QUICK,
label: 'Quick Tunnel',
intent: TUNNEL_INTENT_EPHEMERAL_PUBLIC,
requires: [],
supports: ['sessionTTL'],
stability: 'ga',
},
{
key: TUNNEL_MODE_MANAGED_REMOTE,
label: 'Managed Remote Tunnel',
intent: TUNNEL_INTENT_PERSISTENT_PUBLIC,
requires: ['token', 'hostname'],
supports: ['customDomain', 'sessionTTL'],
stability: 'ga',
},
{
key: TUNNEL_MODE_MANAGED_LOCAL,
label: 'Managed Local Tunnel',
intent: TUNNEL_INTENT_PERSISTENT_PUBLIC,
requires: [],
supports: ['configFile', 'customDomain', 'sessionTTL'],
stability: 'ga',
},
],
};
export function createCloudflareTunnelProvider() {
const validateTokenShape = (value) => {
if (typeof value !== 'string') {
return { ok: false, detail: 'Managed remote token is missing.' };
}
const trimmed = value.trim();
if (!trimmed) {
return { ok: false, detail: 'Managed remote token is missing.' };
}
if (/\s/.test(trimmed)) {
return { ok: false, detail: 'Managed remote token has whitespace; provide the raw token value.' };
}
return { ok: true, detail: 'Managed remote token looks valid.' };
};
const createModeSummary = (checks) => {
const failures = checks.filter((entry) => entry.status === 'fail').length;
const warnings = checks.filter((entry) => entry.status === 'warn').length;
return {
ready: failures === 0,
failures,
warnings,
};
};
const describeMode = ({ mode, checks }) => {
const summary = createModeSummary(checks);
const blockers = checks
.filter((entry) => entry.status === 'fail' && entry.id !== 'startup_readiness')
.map((entry) => entry.detail || entry.label || entry.id);
return {
mode,
checks,
summary,
ready: summary.ready,
blockers,
};
};
return {
id: TUNNEL_PROVIDER_CLOUDFLARE,
capabilities: cloudflareTunnelProviderCapabilities,
checkAvailability: async () => {
const result = await checkCloudflaredAvailable();
if (result.available) {
return result;
}
return {
...result,
message: 'cloudflared is not installed. Install it with: brew install cloudflared',
};
},
diagnose: async (request = {}) => {
const dependency = await checkCloudflaredAvailable();
const network = await checkCloudflareApiReachability();
const providerChecks = [
{
id: 'dependency',
label: 'cloudflared installed',
status: dependency.available ? 'pass' : 'fail',
detail: dependency.available
? (dependency.version || dependency.path || 'cloudflared available')
: 'cloudflared is not installed. Install it with: brew install cloudflared',
},
{
id: 'network',
label: 'Cloudflare API reachable',
status: network.reachable ? 'pass' : 'fail',
detail: network.reachable
? (network.status ? `HTTP ${network.status}` : 'Reachable')
: (network.error || 'Could not reach api.trycloudflare.com'),
},
];
const startupReady = dependency.available && network.reachable;
const startupDetail = startupReady
? 'Provider dependency and network checks passed.'
: 'Resolve provider checks before starting tunnels.';
const quickChecks = [
{
id: 'startup_readiness',
label: 'Provider startup readiness',
status: startupReady ? 'pass' : 'fail',
detail: startupDetail,
},
{
id: 'quick_mode_prerequisites',
label: 'Quick tunnel prerequisites',
status: network.reachable ? 'pass' : 'fail',
detail: network.reachable
? 'Cloudflare edge is reachable for quick tunnels.'
: 'Cloudflare edge is not reachable for quick tunnels.',
},
];
const managedLocalInspection = inspectManagedLocalCloudflareConfig({
configPath: request.configPath,
hostname: request.hostname,
});
const managedLocalChecks = [
{
id: 'startup_readiness',
label: 'Provider startup readiness',
status: startupReady ? 'pass' : 'fail',
detail: startupDetail,
},
{
id: 'managed_local_config',
label: 'Managed local config',
status: managedLocalInspection.ok ? 'pass' : 'fail',
detail: managedLocalInspection.ok
? `${managedLocalInspection.effectiveConfigPath}${managedLocalInspection.resolvedHostname ? ` (${managedLocalInspection.resolvedHostname})` : ''}`
: managedLocalInspection.error,
},
];
const normalizedHost = normalizeCloudflareTunnelHostname(request.hostname);
const hostnameMissing = !normalizedHost;
const remoteTokenValidation = validateTokenShape(request.token);
const tokenMissing = typeof request.token !== 'string' || request.token.trim().length === 0;
const hasSavedManagedRemoteProfile = request.hasSavedManagedRemoteProfile === true;
const tokenProvided = request.tokenProvided === true;
const hostnameProvided = request.hostnameProvided === true;
const hasExplicitManagedRemoteInput = tokenProvided || hostnameProvided;
const canUseSavedProfileForHostname = !hasExplicitManagedRemoteInput && hostnameMissing && hasSavedManagedRemoteProfile;
const canUseSavedProfileForToken = !hasExplicitManagedRemoteInput && tokenMissing && hasSavedManagedRemoteProfile;
const savedProfileReadyDetail = 'at least one saved profile present';
const managedRemoteChecks = [
{
id: 'startup_readiness',
label: 'Provider startup readiness',
status: startupReady ? 'pass' : 'fail',
detail: startupDetail,
},
{
id: 'managed_remote_hostname',
label: 'Managed remote hostname',
status: normalizedHost || canUseSavedProfileForHostname ? 'pass' : 'fail',
detail: normalizedHost
? normalizedHost
: canUseSavedProfileForHostname
? savedProfileReadyDetail
: 'Managed remote hostname is required (use --hostname).',
},
{
id: 'managed_remote_token',
label: 'Managed remote token',
status: remoteTokenValidation.ok || canUseSavedProfileForToken ? 'pass' : 'fail',
detail: canUseSavedProfileForToken
? savedProfileReadyDetail
: remoteTokenValidation.detail,
},
];
const allModes = [
describeMode({ mode: TUNNEL_MODE_QUICK, checks: quickChecks }),
describeMode({ mode: TUNNEL_MODE_MANAGED_REMOTE, checks: managedRemoteChecks }),
describeMode({ mode: TUNNEL_MODE_MANAGED_LOCAL, checks: managedLocalChecks }),
];
const modeFilter = typeof request.mode === 'string' && request.mode.trim().length > 0
? request.mode.trim().toLowerCase()
: null;
const modes = modeFilter ? allModes.filter((entry) => entry.mode === modeFilter) : allModes;
return {
providerChecks,
modes,
};
},
start: async (request, context = {}) => {
if (request.mode === TUNNEL_MODE_MANAGED_REMOTE) {
return startCloudflareManagedRemoteTunnel({
token: request.token,
hostname: request.hostname,
});
}
if (request.mode === TUNNEL_MODE_MANAGED_LOCAL) {
return startCloudflareManagedLocalTunnel({
configPath: request.configPath,
hostname: request.hostname,
});
}
if (!context.originUrl) {
throw new TunnelServiceError('validation_error', 'originUrl is required for quick tunnel mode');
}
return startCloudflareQuickTunnel({
originUrl: context.originUrl,
port: context.activePort,
});
},
stop: (controller) => {
controller?.stop?.();
},
resolvePublicUrl: (controller) => controller?.getPublicUrl?.() ?? null,
getMetadata: (controller) => ({
configPath: controller?.getEffectiveConfigPath?.() ?? null,
resolvedHostname: controller?.getResolvedHostname?.() ?? null,
}),
};
}
@@ -0,0 +1,51 @@
const REQUIRED_PROVIDER_METHODS = ['start', 'stop', 'checkAvailability', 'resolvePublicUrl'];
export function createTunnelProviderRegistry(initialProviders = []) {
const providers = new Map();
let sealed = false;
const register = (provider) => {
if (sealed) {
throw new Error('Tunnel provider registry is sealed; no further registrations allowed');
}
if (!provider || typeof provider.id !== 'string' || provider.id.trim().length === 0) {
throw new Error('Tunnel provider must define a non-empty id');
}
for (const method of REQUIRED_PROVIDER_METHODS) {
if (typeof provider[method] !== 'function') {
throw new Error(`Tunnel provider '${provider.id}' must implement ${method}()`);
}
}
const key = provider.id.trim().toLowerCase();
if (providers.has(key)) {
throw new Error(`Tunnel provider '${key}' is already registered`);
}
providers.set(key, provider);
return provider;
};
const get = (providerId) => {
if (typeof providerId !== 'string' || providerId.trim().length === 0) {
return null;
}
return providers.get(providerId.trim().toLowerCase()) ?? null;
};
const list = () => Array.from(providers.values());
const listCapabilities = () => list().map((provider) => ({ ...provider.capabilities }));
for (const provider of initialProviders) {
register(provider);
}
const seal = () => { sealed = true; };
return {
register,
get,
list,
listCapabilities,
seal,
};
}
+219
View File
@@ -0,0 +1,219 @@
import os from 'os';
import path from 'path';
export const TUNNEL_PROVIDER_CLOUDFLARE = 'cloudflare';
export const TUNNEL_MODE_QUICK = 'quick';
export const TUNNEL_MODE_MANAGED_REMOTE = 'managed-remote';
export const TUNNEL_MODE_MANAGED_LOCAL = 'managed-local';
export const TUNNEL_INTENT_EPHEMERAL_PUBLIC = 'ephemeral-public';
export const TUNNEL_INTENT_PERSISTENT_PUBLIC = 'persistent-public';
export const TUNNEL_INTENT_PRIVATE_NETWORK = 'private-network';
const SUPPORTED_TUNNEL_INTENTS = new Set([
TUNNEL_INTENT_EPHEMERAL_PUBLIC,
TUNNEL_INTENT_PERSISTENT_PUBLIC,
TUNNEL_INTENT_PRIVATE_NETWORK,
]);
const SUPPORTED_TUNNEL_MODES = new Set([
TUNNEL_MODE_QUICK,
TUNNEL_MODE_MANAGED_REMOTE,
TUNNEL_MODE_MANAGED_LOCAL,
]);
export class TunnelServiceError extends Error {
constructor(code, message, details = null) {
super(message);
this.name = 'TunnelServiceError';
this.code = code;
this.details = details;
}
}
const SUPPORTED_TUNNEL_PROVIDERS = new Set([
TUNNEL_PROVIDER_CLOUDFLARE,
]);
export function normalizeTunnelProvider(value) {
if (typeof value !== 'string') {
return TUNNEL_PROVIDER_CLOUDFLARE;
}
const provider = value.trim().toLowerCase();
if (!provider || !SUPPORTED_TUNNEL_PROVIDERS.has(provider)) {
return TUNNEL_PROVIDER_CLOUDFLARE;
}
return provider;
}
export function normalizeTunnelMode(value) {
if (typeof value !== 'string') {
return TUNNEL_MODE_QUICK;
}
const mode = value.trim().toLowerCase();
if (!mode) {
return TUNNEL_MODE_QUICK;
}
if (mode === TUNNEL_MODE_QUICK) {
return TUNNEL_MODE_QUICK;
}
if (mode === TUNNEL_MODE_MANAGED_REMOTE) {
return TUNNEL_MODE_MANAGED_REMOTE;
}
if (mode === TUNNEL_MODE_MANAGED_LOCAL) {
return TUNNEL_MODE_MANAGED_LOCAL;
}
return TUNNEL_MODE_QUICK;
}
export function normalizeTunnelIntent(value) {
if (typeof value !== 'string') {
return undefined;
}
const intent = value.trim().toLowerCase();
if (!intent || !SUPPORTED_TUNNEL_INTENTS.has(intent)) {
return undefined;
}
return intent;
}
function modeIntentFallback(mode) {
if (mode === TUNNEL_MODE_QUICK) {
return TUNNEL_INTENT_EPHEMERAL_PUBLIC;
}
if (mode === TUNNEL_MODE_MANAGED_REMOTE || mode === TUNNEL_MODE_MANAGED_LOCAL) {
return TUNNEL_INTENT_PERSISTENT_PUBLIC;
}
return undefined;
}
function normalizeTunnelModeForRequest(value) {
if (typeof value === 'string') {
const mode = value.trim().toLowerCase();
if (mode === TUNNEL_MODE_QUICK || mode === TUNNEL_MODE_MANAGED_REMOTE || mode === TUNNEL_MODE_MANAGED_LOCAL) {
return mode;
}
}
return TUNNEL_MODE_QUICK;
}
export function normalizeOptionalPath(value) {
if (value === null) {
return null;
}
if (typeof value !== 'string') {
return undefined;
}
const trimmed = value.trim();
if (!trimmed) {
return null;
}
let resolved;
if (trimmed === '~') {
resolved = os.homedir();
} else if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
resolved = path.join(os.homedir(), trimmed.slice(2));
} else {
resolved = path.resolve(trimmed);
}
const home = os.homedir();
if (resolved !== home && !resolved.startsWith(home + path.sep)) {
throw new TunnelServiceError(
'validation_error',
`Config path must be within the home directory (${home}). Got: ${resolved}`
);
}
return resolved;
}
export function isSupportedTunnelMode(mode) {
return SUPPORTED_TUNNEL_MODES.has(mode);
}
export function normalizeTunnelStartRequest(input = {}, defaults = {}) {
const provider = normalizeTunnelProvider(input.provider ?? defaults.provider);
const mode = normalizeTunnelModeForRequest(input.mode ?? defaults.mode);
const explicitIntent = normalizeTunnelIntent(input.intent ?? defaults.intent);
const intent = explicitIntent ?? modeIntentFallback(mode);
const configPathValue = Object.prototype.hasOwnProperty.call(input, 'configPath')
? input.configPath
: defaults.configPath;
const configPath = normalizeOptionalPath(configPathValue);
const token = typeof (input.token ?? defaults.token) === 'string'
? (input.token ?? defaults.token).trim()
: '';
const hostname = typeof (input.hostname ?? defaults.hostname) === 'string'
? (input.hostname ?? defaults.hostname).trim().toLowerCase()
: '';
return {
provider,
mode,
intent,
configPath,
token,
hostname,
};
}
export function validateTunnelStartRequest(request, capabilities) {
if (!request || typeof request !== 'object') {
throw new TunnelServiceError('validation_error', 'Tunnel start request must be an object');
}
if (!request.provider) {
throw new TunnelServiceError('validation_error', 'Tunnel provider is required');
}
if (!isSupportedTunnelMode(request.mode)) {
throw new TunnelServiceError('mode_unsupported', `Unsupported tunnel mode: ${request.mode}`);
}
if (!capabilities || capabilities.provider !== request.provider) {
throw new TunnelServiceError('provider_unsupported', `Unsupported tunnel provider: ${request.provider}`);
}
if (!Array.isArray(capabilities.modes)) {
throw new TunnelServiceError('mode_unsupported', `Provider '${request.provider}' does not declare tunnel modes`);
}
const modeDescriptor = capabilities.modes.find((entry) => entry?.key === request.mode);
if (!modeDescriptor) {
throw new TunnelServiceError('mode_unsupported', `Provider '${request.provider}' does not support mode '${request.mode}'`);
}
if (typeof request.intent === 'string' && request.intent.length > 0) {
if (!SUPPORTED_TUNNEL_INTENTS.has(request.intent)) {
throw new TunnelServiceError('validation_error', `Unsupported tunnel intent: ${request.intent}`);
}
if (modeDescriptor.intent !== request.intent) {
throw new TunnelServiceError(
'validation_error',
`Tunnel intent '${request.intent}' does not match mode '${request.mode}' (expected '${modeDescriptor.intent}')`
);
}
}
const requiredFields = Array.isArray(modeDescriptor.requires) ? modeDescriptor.requires : [];
if (requiredFields.includes('token')) {
if (!request.token) {
throw new TunnelServiceError('validation_error', 'Managed remote tunnel token is required');
}
}
if (requiredFields.includes('hostname')) {
if (!request.hostname) {
throw new TunnelServiceError('validation_error', 'Managed remote tunnel hostname is required');
}
}
if (requiredFields.includes('configPath')) {
if (request.configPath === undefined || request.configPath === null || request.configPath === '') {
throw new TunnelServiceError('validation_error', `Mode '${request.mode}' requires a configPath`);
}
}
}