Files
openchamber/packages/web/server/lib/tunnels/index.js
T
Iuliia Ivashko 63f1698cdd 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>
2026-03-12 19:40:22 +02:00

167 lines
4.7 KiB
JavaScript

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,
};
}