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
+10 -1
View File
@@ -25,4 +25,13 @@ export declare function startWebUiServer(
export declare function gracefulShutdown(options?: { exitProcess?: boolean }): Promise<void>;
export declare function setupProxy(app: Express): void;
export declare function restartOpenCode(): Promise<void>;
export declare function parseArgs(argv?: string[]): { port: number; uiPassword: string | null };
export declare function parseArgs(argv?: string[]): {
port: number;
uiPassword: string | null;
tryCfTunnel: boolean;
tunnelProvider?: string;
tunnelMode?: string;
tunnelConfigPath?: string | null;
tunnelToken?: string;
tunnelHostname?: string;
};
File diff suppressed because it is too large Load Diff
+398 -27
View File
@@ -3,6 +3,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import yaml from 'yaml';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -10,6 +11,11 @@ const __dirname = path.dirname(__filename);
const TRY_CF_URL_REGEX = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/i;
const DEFAULT_STARTUP_TIMEOUT_MS = 30000;
const MANAGED_TUNNEL_STARTUP_TIMEOUT_MS = 20000;
const MANAGED_TUNNEL_LIVENESS_FALLBACK_MS = 6000;
const TUNNEL_MODE_QUICK = 'quick';
const TUNNEL_MODE_MANAGED_REMOTE = 'managed-remote';
const TUNNEL_MODE_MANAGED_LOCAL = 'managed-local';
async function searchPathFor(command) {
const pathValue = process.env.PATH || '';
@@ -88,7 +94,7 @@ Or visit: https://developers.cloudflare.com/cloudflare-one/networks/connectors/c
`);
}
const spawnCloudflared = (args, envOverrides = {}) => spawn('cloudflared', args, {
const spawnCloudflared = (args, envOverrides = {}, resolvedBinaryPath = 'cloudflared') => spawn(resolvedBinaryPath, args, {
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env,
@@ -98,6 +104,280 @@ const spawnCloudflared = (args, envOverrides = {}) => spawn('cloudflared', args,
killSignal: 'SIGINT',
});
const normalizeHostname = (value) => {
if (typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (!trimmed) {
return null;
}
try {
const parsed = trimmed.includes('://') ? new URL(trimmed) : new URL(`https://${trimmed}`);
const hostname = parsed.hostname.trim().toLowerCase();
if (!hostname || hostname.includes('*')) {
return null;
}
return hostname;
} catch {
return null;
}
};
export function normalizeCloudflareTunnelHostname(value) {
return normalizeHostname(value);
}
export async function checkCloudflareApiReachability({ fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
if (typeof fetchImpl !== 'function') {
return {
reachable: false,
status: null,
error: 'Fetch API is unavailable in this runtime.',
};
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetchImpl('https://api.trycloudflare.com/', {
method: 'GET',
signal: controller.signal,
});
return {
reachable: true,
status: response.status,
error: null,
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
reachable: false,
status: null,
error: message,
};
} finally {
clearTimeout(timeout);
}
}
const READY_LOG_PATTERNS = [
/registered tunnel connection/i,
/connection[^\n]*registered/i,
/starting metrics server/i,
/connected to edge/i,
];
const MANAGED_LOCAL_CONFIG_MAX_BYTES = 256 * 1024;
const MANAGED_LOCAL_CONFIG_ALLOWED_EXTENSIONS = new Set(['.yml', '.yaml', '.json']);
const FATAL_LOG_PATTERNS = [
/error parsing.*config/i,
/failed to .*config/i,
/invalid token/i,
/unauthorized/i,
/credentials file .* not found/i,
/provided tunnel credentials are invalid/i,
];
function isCloudflaredReadyLogLine(line) {
if (!line) {
return false;
}
return READY_LOG_PATTERNS.some((pattern) => pattern.test(line));
}
function isCloudflaredFatalLogLine(line) {
if (!line) {
return false;
}
return FATAL_LOG_PATTERNS.some((pattern) => pattern.test(line));
}
function assertReadableFile(filePath, contextLabel) {
let stats;
try {
stats = fs.statSync(filePath);
} catch {
throw new Error(`${contextLabel} file was not found. Select a valid cloudflared config file.`);
}
if (!stats.isFile()) {
throw new Error(`${contextLabel} path is not a file. Select a cloudflared config file.`);
}
const extension = path.extname(filePath).toLowerCase();
if (!MANAGED_LOCAL_CONFIG_ALLOWED_EXTENSIONS.has(extension)) {
throw new Error(`${contextLabel} must be a .yml, .yaml, or .json file.`);
}
if (stats.size <= 0) {
throw new Error(`${contextLabel} file is empty.`);
}
if (stats.size > MANAGED_LOCAL_CONFIG_MAX_BYTES) {
throw new Error(`${contextLabel} file is too large (max ${MANAGED_LOCAL_CONFIG_MAX_BYTES} bytes).`);
}
try {
fs.accessSync(filePath, fs.constants.R_OK);
} catch {
throw new Error(`${contextLabel} file is not readable. Check file permissions and try again.`);
}
}
function extractHostnameFromCloudflaredConfigDetailed(configPath) {
if (typeof configPath !== 'string' || configPath.trim().length === 0) {
return { hostname: null, parseError: null };
}
let raw;
try {
raw = fs.readFileSync(configPath, 'utf8');
} catch {
return {
hostname: null,
parseError: new Error('Could not read the managed local tunnel config file. Check that the file exists and is accessible.'),
};
}
let parsed;
try {
parsed = yaml.parse(raw);
} catch {
return {
hostname: null,
parseError: new Error('Managed local tunnel config is invalid. Use a valid cloudflared YAML/JSON config file.'),
};
}
const ingress = Array.isArray(parsed?.ingress) ? parsed.ingress : [];
for (const rule of ingress) {
const hostname = normalizeHostname(rule?.hostname);
if (hostname) {
return { hostname, parseError: null };
}
}
return { hostname: null, parseError: null };
}
const extractHostnameFromCloudflaredConfig = (configPath) => {
return extractHostnameFromCloudflaredConfigDetailed(configPath).hostname;
};
const getDefaultCloudflaredConfigPath = () => path.join(os.homedir(), '.cloudflared', 'config.yml');
export function inspectManagedLocalCloudflareConfig({ configPath, hostname } = {}) {
const requestedPath = typeof configPath === 'string' ? configPath.trim() : '';
const effectiveConfigPath = requestedPath || getDefaultCloudflaredConfigPath();
try {
if (requestedPath) {
assertReadableFile(effectiveConfigPath, 'Managed local tunnel config');
} else {
assertReadableFile(effectiveConfigPath, 'Managed local tunnel default config');
}
} catch (error) {
return {
ok: false,
effectiveConfigPath,
resolvedHostname: null,
error: error instanceof Error ? error.message : String(error),
};
}
const configHostnameResult = extractHostnameFromCloudflaredConfigDetailed(effectiveConfigPath);
if (configHostnameResult.parseError) {
return {
ok: false,
effectiveConfigPath,
resolvedHostname: null,
error: configHostnameResult.parseError.message,
};
}
const resolvedHostname = normalizeHostname(hostname) || configHostnameResult.hostname;
if (!resolvedHostname) {
return {
ok: false,
effectiveConfigPath,
resolvedHostname: null,
error: 'Managed local tunnel hostname is required (set --hostname or include ingress hostname in config).',
};
}
return {
ok: true,
effectiveConfigPath,
resolvedHostname,
error: null,
};
}
async function waitForManagedTunnelReady(child, { modeLabel }) {
await new Promise((resolve, reject) => {
let settled = false;
let sawOutput = false;
const finish = (handler, value) => {
if (settled) {
return;
}
settled = true;
clearTimeout(fallbackTimer);
clearTimeout(hardTimeout);
child.stdout?.off('data', onStdout);
child.stderr?.off('data', onStderr);
child.off('exit', onExit);
handler(value);
};
const inspectChunk = (chunk) => {
const text = chunk.toString('utf8');
if (text.trim().length > 0) {
sawOutput = true;
}
const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
for (const line of lines) {
if (isCloudflaredReadyLogLine(line)) {
finish(resolve, null);
return;
}
if (isCloudflaredFatalLogLine(line)) {
finish(reject, new Error(`Cloudflared failed to start ${modeLabel}: ${line}`));
return;
}
}
};
const onStdout = (chunk) => {
inspectChunk(chunk);
};
const onStderr = (chunk) => {
inspectChunk(chunk);
};
const onExit = (code) => {
finish(reject, new Error(`Cloudflared exited while starting ${modeLabel} (code ${code ?? 'unknown'})`));
};
child.stdout?.on('data', onStdout);
child.stderr?.on('data', onStderr);
child.once('exit', onExit);
const fallbackTimer = setTimeout(() => {
if (sawOutput) {
finish(resolve, null);
}
}, MANAGED_TUNNEL_LIVENESS_FALLBACK_MS);
const hardTimeout = setTimeout(() => {
finish(reject, new Error(`Timed out waiting for cloudflared to initialize ${modeLabel}. Check your tunnel config and credentials.`));
}, MANAGED_TUNNEL_STARTUP_TIMEOUT_MS);
});
}
export async function startCloudflareQuickTunnel({ originUrl }) {
const cfCheck = await checkCloudflaredAvailable();
@@ -110,7 +390,7 @@ export async function startCloudflareQuickTunnel({ originUrl }) {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-cf-'));
const child = spawnCloudflared(['tunnel', '--url', originUrl], { HOME: tempDir });
const child = spawnCloudflared(['tunnel', '--url', originUrl], { HOME: tempDir }, cfCheck.path);
let publicUrl = null;
let tunnelReady = false;
@@ -150,6 +430,8 @@ export async function startCloudflareQuickTunnel({ originUrl }) {
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
if (!publicUrl) {
try { child.kill('SIGINT'); } catch { /* ignore */ }
cleanupTempDir();
reject(new Error('Tunnel URL not received within 30 seconds'));
}
}, DEFAULT_STARTUP_TIMEOUT_MS);
@@ -173,7 +455,7 @@ export async function startCloudflareQuickTunnel({ originUrl }) {
});
return {
mode: 'quick',
mode: TUNNEL_MODE_QUICK,
stop: () => {
try {
child.kill('SIGINT');
@@ -186,7 +468,7 @@ export async function startCloudflareQuickTunnel({ originUrl }) {
};
}
export async function startCloudflareNamedTunnel({ token, hostname }) {
export async function startCloudflareManagedRemoteTunnel({ token, hostname, tokenFilePath }) {
const cfCheck = await checkCloudflaredAvailable();
if (!cfCheck.available) {
@@ -198,17 +480,114 @@ export async function startCloudflareNamedTunnel({ token, hostname }) {
const normalizedHost = typeof hostname === 'string' ? hostname.trim().toLowerCase() : '';
if (!normalizedToken) {
throw new Error('Named tunnel token is required');
throw new Error('Managed remote tunnel token is required');
}
if (!normalizedHost) {
throw new Error('Named tunnel hostname is required');
throw new Error('Managed remote tunnel hostname is required');
}
const child = spawnCloudflared(['tunnel', 'run', '--token', normalizedToken]);
let effectiveTokenFilePath = typeof tokenFilePath === 'string' ? tokenFilePath : null;
let tempTokenFile = null;
if (!effectiveTokenFilePath) {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-cf-token-'));
effectiveTokenFilePath = path.join(tempDir, 'token');
fs.writeFileSync(effectiveTokenFilePath, normalizedToken, { encoding: 'utf8', mode: 0o600 });
tempTokenFile = { dir: tempDir, path: effectiveTokenFilePath };
}
const child = spawnCloudflared(['tunnel', 'run', '--token-file', effectiveTokenFilePath], {}, cfCheck.path);
const publicUrl = `https://${normalizedHost}`;
let exitedEarly = false;
let earlyExitCode = null;
child.stdout.on('data', () => {
// Keep stream drained, but avoid logging potentially sensitive output.
});
child.stderr.on('data', (chunk) => {
const text = chunk.toString('utf8');
process.stderr.write(text);
});
const cleanupTempTokenFile = () => {
if (tempTokenFile) {
try {
if (fs.existsSync(tempTokenFile.dir)) {
fs.rmSync(tempTokenFile.dir, { recursive: true, force: true });
}
} catch {
// Ignore cleanup errors
}
}
};
child.on('error', (error) => {
console.error(`Cloudflared error: ${error.message}`);
cleanupTempTokenFile();
});
child.on('exit', () => {
cleanupTempTokenFile();
});
try {
await waitForManagedTunnelReady(child, { modeLabel: 'managed-remote tunnel' });
} catch (error) {
try { child.kill('SIGINT'); } catch { /* ignore */ }
cleanupTempTokenFile();
throw error;
}
return {
mode: TUNNEL_MODE_MANAGED_REMOTE,
stop: () => {
try {
child.kill('SIGINT');
} catch {
// Ignore
}
cleanupTempTokenFile();
},
process: child,
getPublicUrl: () => publicUrl,
};
}
export async function startCloudflareManagedLocalTunnel({ configPath, hostname }) {
const cfCheck = await checkCloudflaredAvailable();
if (!cfCheck.available) {
printCloudflareTunnelInstallHelp();
throw new Error('cloudflared is not installed');
}
const requestedPath = typeof configPath === 'string' ? configPath.trim() : '';
const effectiveConfigPath = requestedPath || getDefaultCloudflaredConfigPath();
if (requestedPath) {
assertReadableFile(effectiveConfigPath, 'Managed local tunnel config');
} else {
assertReadableFile(effectiveConfigPath, 'Managed local tunnel default config');
}
const configHostnameResult = extractHostnameFromCloudflaredConfigDetailed(effectiveConfigPath);
if (configHostnameResult.parseError) {
throw configHostnameResult.parseError;
}
const resolvedHost = normalizeHostname(hostname) || configHostnameResult.hostname;
if (!resolvedHost) {
throw new Error('Managed local tunnel hostname is required (use --tunnel-hostname or add an ingress hostname to the cloudflared config)');
}
const args = ['tunnel'];
if (requestedPath) {
args.push('--config', effectiveConfigPath);
}
args.push('run');
const child = spawnCloudflared(args, {}, cfCheck.path);
const publicUrl = `https://${resolvedHost}`;
child.stdout.on('data', () => {
// Keep stream drained, but avoid logging potentially sensitive output.
@@ -223,25 +602,15 @@ export async function startCloudflareNamedTunnel({ token, hostname }) {
console.error(`Cloudflared error: ${error.message}`);
});
await new Promise((resolve, reject) => {
const readyTimer = setTimeout(() => {
if (exitedEarly) {
reject(new Error(`Cloudflared exited early with code ${earlyExitCode ?? 'unknown'}`));
} else {
resolve(null);
}
}, 2000);
child.once('exit', (code) => {
exitedEarly = true;
earlyExitCode = code;
clearTimeout(readyTimer);
reject(new Error(`Cloudflared exited with code ${code ?? 'unknown'}`));
});
});
try {
await waitForManagedTunnelReady(child, { modeLabel: 'managed-local tunnel' });
} catch (error) {
try { child.kill('SIGINT'); } catch { /* ignore */ }
throw error;
}
return {
mode: 'named',
mode: TUNNEL_MODE_MANAGED_LOCAL,
stop: () => {
try {
child.kill('SIGINT');
@@ -251,6 +620,8 @@ export async function startCloudflareNamedTunnel({ token, hostname }) {
},
process: child,
getPublicUrl: () => publicUrl,
getResolvedHostname: () => resolvedHost,
getEffectiveConfigPath: () => effectiveConfigPath,
};
}
@@ -268,7 +639,7 @@ export function printTunnelWarning() {
• URLs are temporary and will expire when the tunnel stops
• Password protection is required for tunnel access
For production use, set up a named Cloudflare Tunnel:
For production use, set up a managed remote Cloudflare Tunnel:
https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/
`);
}
+5 -4
View File
@@ -258,7 +258,6 @@ export async function getLatestVersion() {
const data = await response.json();
return data['dist-tags']?.latest || null;
} catch (error) {
console.warn('Failed to fetch latest version from npm:', error.message);
return null;
}
}
@@ -345,10 +344,12 @@ export async function checkForUpdates() {
/**
* Execute the update (used by CLI)
*/
export function executeUpdate(pm = detectPackageManager()) {
export function executeUpdate(pm = detectPackageManager(), options = {}) {
const command = getUpdateCommand(pm);
console.log(`Updating ${PACKAGE_NAME} using ${pm}...`);
console.log(`Running: ${command}`);
if (!options?.silent) {
console.log(`Updating ${PACKAGE_NAME} using ${pm}...`);
console.log(`Running: ${command}`);
}
const result = spawnSync(command, {
stdio: 'inherit',
+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`);
}
}
}