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:
@@ -0,0 +1,216 @@
|
||||
---
|
||||
name: clack-cli-patterns
|
||||
description: Use when creating or modifying terminal CLI commands, prompts, or output formatting in OpenChamber. Enforces Clack UX standards with strict parity and safety across TTY/non-TTY, --quiet, and --json modes.
|
||||
license: MIT
|
||||
compatibility: opencode
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
OpenChamber terminal CLI uses `@clack/prompts` for interactive UX, but command policy and validation must be mode-agnostic.
|
||||
|
||||
**Core principle:** policy-first, UX-second. Clack is presentation, not enforcement.
|
||||
|
||||
## Scope
|
||||
|
||||
Use this skill for terminal CLI work only (for example `packages/web/bin/*`).
|
||||
|
||||
Do not use this skill for web UI or VS Code webview styling work.
|
||||
|
||||
## Mandatory Rules
|
||||
|
||||
1. **Validation first**
|
||||
- Safety and correctness checks must run in all modes.
|
||||
- Prompts may help collect input, but cannot be the only guard.
|
||||
|
||||
2. **Mode parity is required**
|
||||
- Behavior must be equivalent in:
|
||||
- Interactive TTY
|
||||
- Non-interactive shells
|
||||
- `--quiet`
|
||||
- `--json`
|
||||
- Fully pre-specified flags
|
||||
- Invalid operations must fail deterministically with non-zero exit code.
|
||||
|
||||
3. **Prompt guard contract**
|
||||
- Only prompt when all are true:
|
||||
- stdout is TTY
|
||||
- not `--quiet`
|
||||
- not `--json`
|
||||
- not automated/non-interactive context
|
||||
|
||||
4. **Output contract**
|
||||
- `--json`: machine-readable output only.
|
||||
- `--quiet`: suppress non-essential output only.
|
||||
- Neither mode weakens policy enforcement.
|
||||
|
||||
5. **Cancellation contract**
|
||||
- Handle prompt cancellation with `isCancel` + `cancel(...)`.
|
||||
- Handle SIGINT cleanly and use consistent exit semantics.
|
||||
|
||||
## Clack Primitive Standard
|
||||
|
||||
- **Flow framing:** `intro`, `outro`, `cancel`
|
||||
- **Status lines:** `log.info`, `log.success`, `log.warn`, `log.error`, `log.step`
|
||||
- **Guidance blocks:**
|
||||
- default: `note`
|
||||
- high-severity warnings only: `box`
|
||||
- **Prompts:** `select`, `confirm`, `text`, `password`
|
||||
- **Long-running feedback:**
|
||||
- unknown duration: `spinner`
|
||||
- known duration: `progress`
|
||||
- multi-stage: `tasks`
|
||||
|
||||
## Preferred Pattern
|
||||
|
||||
Centralize Clack imports and formatting helpers in one adapter module (for example `cli-output.js`) so command logic stays focused on behavior and policy.
|
||||
|
||||
### Thin framework (recommended)
|
||||
|
||||
Use a small shared helper surface rather than command-specific formatting logic.
|
||||
|
||||
- `isJsonMode(options)`
|
||||
- `isQuietMode(options)`
|
||||
- `shouldRenderHumanOutput(options)`
|
||||
- `canPrompt(options)`
|
||||
- `createSpinner(options)`
|
||||
- `createProgress(options, config)`
|
||||
- `printJson(payload)`
|
||||
|
||||
Keep this layer minimal. Do not hide core validation or command semantics inside output helpers.
|
||||
|
||||
## Output Contracts by Mode
|
||||
|
||||
### `--quiet` contract
|
||||
|
||||
`--quiet` should still return essential result data.
|
||||
|
||||
- Read/list commands: emit concise machine-friendly lines (not framed Clack blocks).
|
||||
- Action commands: emit one minimal success line and concise errors.
|
||||
- Do not suppress required outcomes entirely.
|
||||
|
||||
Quiet output should still be complete enough for scripts and quick human scanning.
|
||||
|
||||
- Status-like commands should list all active items, not only `running`/`ok`.
|
||||
- Prefer compact stable key tokens in quiet lines (for example `port 3000 pass:yes`).
|
||||
|
||||
### `--json` contract (strict)
|
||||
|
||||
- Output must be JSON only (no extra text before/after payload).
|
||||
- Warnings/info should be represented in JSON fields (for example `status`, `messages`).
|
||||
- Preserve non-zero exit codes for failures.
|
||||
|
||||
## Human UX Consistency
|
||||
|
||||
### Framing completeness
|
||||
|
||||
- If human flow uses `intro`, close with `outro` (or `outro('')` when you want structure without text).
|
||||
- Avoid orphan frame/spinner artifacts (prefer `spinner.clear()` when a trailing spinner line is not wanted).
|
||||
- If a structured summary section immediately follows a spinner, prefer `spinner.clear()` to avoid duplicate success lines.
|
||||
|
||||
### Progress feedback for visible operations
|
||||
|
||||
- For operations users wait on (start/stop/restart/tunnel lifecycle), show in-progress spinner in interactive mode.
|
||||
- Resolve each spinner explicitly to done/error so users can see completion state at the same visual location.
|
||||
- Keep quiet/json modes non-animated.
|
||||
|
||||
### Prompt flow design
|
||||
|
||||
- Ask required inputs in dependency order (for example hostname before token when token depends on chosen host/mode context).
|
||||
- When offering save-vs-run flows, ask intent before collecting optional metadata (for example profile name only if user chooses save).
|
||||
- Prefill editable values with `initialValue` (not only `placeholder`) so users can accept or edit quickly.
|
||||
- Reuse latest relevant values when safe (for example last managed-local config path, last managed-remote hostname).
|
||||
|
||||
### Readability on narrow terminals
|
||||
|
||||
- Prefer short lines.
|
||||
- Split long guidance into multiple detail lines.
|
||||
- Use warning/info codes (`[CODE]`) when the message has follow-up docs or repeat use.
|
||||
|
||||
### Guidance tone
|
||||
|
||||
- Use `Optional Tips` for non-required next actions.
|
||||
- Avoid wording that implies mandatory follow-up unless it is truly required.
|
||||
|
||||
### Guidance rendering style (preferred)
|
||||
|
||||
- Prefer structured status lines for reusable hints:
|
||||
- `logStatus('info', '[CODE]', '<actionable command or short guidance>')`
|
||||
- Use short, stable codes (for example `[START_PROFILE]`, `[PORT_MISMATCH]`) so users can quickly scan and recognize repeated guidance.
|
||||
- Prefer this style over boxed notes for routine follow-up actions.
|
||||
- Reserve `note`/boxed callouts for rare, high-context guidance where a long paragraph is truly necessary.
|
||||
|
||||
## Parity Verification Matrix
|
||||
|
||||
For each command/subcommand, manually verify:
|
||||
|
||||
1. default interactive TTY output
|
||||
2. `--quiet` output (minimal but informative)
|
||||
3. `--json` output (JSON-only)
|
||||
4. non-TTY behavior (e.g. piped)
|
||||
5. error path in both human and json modes
|
||||
|
||||
## Copy/Paste Snippets
|
||||
|
||||
### Prompt Guard
|
||||
|
||||
```js
|
||||
if (canPrompt(options)) {
|
||||
const value = await select({
|
||||
message: 'Choose an option',
|
||||
options: [{ value: 'a', label: 'Option A' }],
|
||||
});
|
||||
if (isCancel(value)) {
|
||||
cancel('Operation cancelled.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Non-Interactive Fallback
|
||||
|
||||
```js
|
||||
if (!resolvedValue) {
|
||||
if (canPrompt(options)) {
|
||||
// prompt path
|
||||
} else {
|
||||
throw new Error('Missing required value. Provide --flag <value>.');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Spinner Guard
|
||||
|
||||
```js
|
||||
const spin = createSpinner(options);
|
||||
spin?.start('Running operation...');
|
||||
// ...work...
|
||||
spin?.stop('Done');
|
||||
```
|
||||
|
||||
### JSON vs Human Output
|
||||
|
||||
```js
|
||||
if (options.json) {
|
||||
printJson({ ok: true, data });
|
||||
return;
|
||||
}
|
||||
|
||||
intro('Operation');
|
||||
log.success('Completed');
|
||||
outro('done');
|
||||
```
|
||||
|
||||
## Implementation Checklist
|
||||
|
||||
1. Add or update core validators first.
|
||||
2. Ensure validators execute in all modes.
|
||||
3. Add interactive Clack UX only as enhancement.
|
||||
4. Verify parity between interactive and non-interactive flows.
|
||||
5. Ensure script-safe deterministic failure behavior.
|
||||
|
||||
## References
|
||||
|
||||
- Policy source: `AGENTS.md` (CLI Parity and Safety Policy)
|
||||
- Terminal CLI precedent: `packages/web/bin/cli.js`
|
||||
- Output adapter precedent: `packages/web/bin/cli-output.js`
|
||||
@@ -119,6 +119,50 @@ All scripts are in `package.json`.
|
||||
- No new deps unless asked.
|
||||
- Never add secrets (`.env`, keys) or log sensitive data.
|
||||
|
||||
## CLI Parity and Safety Policy (MANDATORY)
|
||||
|
||||
### Principle: policy-first, UX-second
|
||||
|
||||
All safety and correctness rules MUST be enforced in core command logic, independent of output mode.
|
||||
|
||||
Interactive/pretty UX (`@clack/prompts`) is a presentation layer only.
|
||||
It must never be the only place where validation or restriction is enforced.
|
||||
|
||||
### Required parity across modes
|
||||
|
||||
The same functional outcome and safety gates MUST hold for all execution modes:
|
||||
|
||||
- Interactive TTY (full Clack UX)
|
||||
- Non-interactive shells (piped/stdin-less automation)
|
||||
- `--quiet`
|
||||
- `--json`
|
||||
- Fully pre-specified flags (no prompts)
|
||||
|
||||
In all modes, invalid operations MUST fail with non-zero exit code and deterministic error semantics.
|
||||
|
||||
### Non-negotiable rule
|
||||
|
||||
Do not rely on prompts to enforce policy.
|
||||
|
||||
- Prompts MAY help users choose valid inputs.
|
||||
- Core validators MUST run even when prompts are unavailable or skipped.
|
||||
- `--quiet` suppresses non-essential output only; it does not weaken validation.
|
||||
- `--json` changes output shape only; it does not weaken validation.
|
||||
|
||||
Detailed Clack UX patterns (primitives, prompt gating, and implementation checklist)
|
||||
are defined in the `clack-cli-patterns` skill and should not be duplicated here.
|
||||
|
||||
## Clack CLI Skill (MANDATORY for terminal CLI work)
|
||||
|
||||
When working on terminal CLI commands, prompts, or output formatting, agents **MUST** study the Clack CLI skill first.
|
||||
|
||||
**Before starting terminal CLI work:**
|
||||
```
|
||||
skill({ name: "clack-cli-patterns" })
|
||||
```
|
||||
|
||||
Scope: terminal CLI only (for example `packages/web/bin/*`). Do not apply this requirement to VS Code or web UI work.
|
||||
|
||||
## Theme System (MANDATORY for UI work)
|
||||
|
||||
When working on any UI components, styling, or visual changes, agents **MUST** study the theme system skill first.
|
||||
|
||||
@@ -28,7 +28,53 @@
|
||||
|
||||
</details>
|
||||
|
||||
## Highlights
|
||||
## Why use OpenChamber?
|
||||
|
||||
- **Cross-device continuity**: Start in TUI, continue on tablet/phone, return to terminal - same session
|
||||
- **Remote access**: Use OpenCode from anywhere via browser
|
||||
- **Familiarity**: A visual alternative for developers who prefer GUI workflows
|
||||
|
||||
## Features
|
||||
|
||||
### Core (all app versions)
|
||||
|
||||
- Branchable chat timeline with `/undo`, `/redo`, and one-click forks from earlier turns
|
||||
- Smart tool UIs for diffs, file operations, permissions, and long-running task progress
|
||||
- Voice mode with speech input and read-aloud responses for hands-free workflows
|
||||
- Multi-agent runs from one prompt with isolated worktrees for safe side-by-side comparisons
|
||||
- Git workflows in-app: identities, commits, PR creation, checks, and merge actions
|
||||
- GitHub-native workflows: start sessions from issues and pull requests with context already attached
|
||||
- Plan/Build mode with a dedicated plan view for drafting and iterating implementation steps
|
||||
- Inline comment drafts on diffs, files, and plans that can be sent back to the agent
|
||||
- Context visibility tools (token/cost breakdowns, raw message inspection, and activity summaries)
|
||||
- Integrated terminal with per-directory sessions and stable performance on heavy output
|
||||
- Built-in skills catalog and local skill management for reusable automation workflows
|
||||
|
||||
### Web / PWA
|
||||
|
||||
- Provider-aware tunnel access model with Cloudflare `quick`, `managed-remote`, and `managed-local` modes
|
||||
- One-scan onboarding with tunnel QR + password URL helpers
|
||||
- Mobile-first experience: optimized chat controls, keyboard-safe layouts, and attachment-friendly UI
|
||||
- Background notifications plus reliable cross-tab session activity tracking
|
||||
- Built-in self-update + restart flow that keeps your server settings intact
|
||||
|
||||
### Desktop (macOS)
|
||||
|
||||
- Native macOS menu integration with polished app actions and deep-link handling
|
||||
- Multi-window support for parallel project/session workflows
|
||||
- "Open In" shortcuts for Finder, Terminal, and your preferred editor
|
||||
- Fast switching between local and remote instances
|
||||
- Workspace-first startup flow with directory picker and steadier window restore behavior
|
||||
|
||||
### VS Code Extension
|
||||
|
||||
- Editor-native workflow: open files directly from tool output and keep sessions beside your code
|
||||
- Agent Manager for parallel multi-model runs from a single prompt
|
||||
- Right-click actions to add context, explain selections, and improve code in-place
|
||||
- In-extension settings, responsive layout, and theme mapping that matches your editor
|
||||
- Hardened runtime lifecycle and health checks for faster startup and fewer stuck reconnect states
|
||||
|
||||
### Custom Themes
|
||||
|
||||
- **Use it from anywhere** - Cloudflare tunnel with QR code onboarding. Scan, connect, code from your couch.
|
||||
- **Branchable chat timeline** - Undo, redo, fork from any turn. Explore different approaches without losing your place.
|
||||
@@ -59,11 +105,18 @@ openchamber --ui-password be-creative-here --daemon
|
||||
|
||||
```bash
|
||||
openchamber --port 8080 # Custom port
|
||||
openchamber --daemon # Background mode
|
||||
openchamber --ui-password secret # Password-protect UI
|
||||
openchamber --try-cf-tunnel # Cloudflare Quick Tunnel
|
||||
openchamber --try-cf-tunnel --tunnel-qr # + QR code
|
||||
openchamber --try-cf-tunnel --tunnel-password-url # + password in URL
|
||||
openchamber tunnel help # Tunnel lifecycle commands
|
||||
openchamber tunnel providers # Show provider capabilities
|
||||
openchamber tunnel profile add --provider cloudflare --mode managed-remote --name prod-main --hostname app.example.com --token <token>
|
||||
openchamber tunnel start --profile prod-main
|
||||
openchamber tunnel start --provider cloudflare --mode quick --qr
|
||||
openchamber tunnel start --provider cloudflare --mode managed-local --config ~/.cloudflared/config.yml
|
||||
openchamber tunnel status --all # Show tunnel state across instances
|
||||
openchamber tunnel stop --port 3000 # Stop tunnel only (server stays running)
|
||||
openchamber logs # Follow latest instance logs
|
||||
OPENCODE_PORT=4096 OPENCODE_SKIP_START=true openchamber # Connect to external OpenCode server
|
||||
OPENCODE_HOST=https://myhost:4096 OPENCODE_SKIP_START=true openchamber # Connect via custom host/HTTPS
|
||||
openchamber stop # Stop server
|
||||
openchamber update # Update to latest
|
||||
```
|
||||
@@ -103,7 +156,24 @@ environment:
|
||||
| `qr` | Enable tunnel + QR code |
|
||||
| `password` | Enable tunnel + password in URL |
|
||||
|
||||
**Data directory permissions:** The `data/` directory is mounted for persistent storage. Before running:
|
||||
### Managed Cloudflare Tunnel (persistent hostname)
|
||||
|
||||
OpenChamber also supports managed-remote mode for more reliable long-lived access with your Cloudflare account and custom hostname.
|
||||
|
||||
- Configure it in-app at **Settings -> OpenChamber -> Tunnel** and switch mode to **Managed Remote Tunnel**.
|
||||
- Managed-remote tunnels require a domain in your Cloudflare account.
|
||||
- Cloudflare setup guide: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/
|
||||
- Managed-local mode uses your local cloudflared config, for example:
|
||||
- `openchamber tunnel start --provider cloudflare --mode managed-local --config ~/.cloudflared/config.yml`
|
||||
|
||||
### Tunnel behavior notes
|
||||
|
||||
- OpenChamber supports one active tunnel per running instance (port).
|
||||
- Starting a tunnel with a different mode/provider on the same instance replaces the current tunnel.
|
||||
- Replacing or stopping a tunnel revokes existing connect links and invalidates remote tunnel sessions for that instance.
|
||||
- Connect links are one-time tokens; generating a new link revokes the previous unused link.
|
||||
|
||||
**Data Directory Permission Note:** The `data/` directory is mounted into the container for persistent storage (config, sessions, SSH keys, workspaces). Before running, ensure the directory exists and has proper permissions:
|
||||
|
||||
```bash
|
||||
mkdir -p data/openchamber data/opencode/share data/opencode/config data/ssh
|
||||
@@ -117,6 +187,9 @@ chown -R 1000:1000 data/
|
||||
<details>
|
||||
<summary>Named Cloudflare Tunnel (persistent hostname)</summary>
|
||||
|
||||
- [OpenCode CLI](https://opencode.ai) installed
|
||||
- Node.js 20+ (for web version)
|
||||
- [cloudflared](https://github.com/cloudflare/cloudflared/releases) (required for Cloudflare tunnel modes)
|
||||
For reliable long-lived access with a custom hostname from your Cloudflare account:
|
||||
|
||||
- Configure in-app at **Settings > OpenChamber > Tunnel**, switch to **Named** mode.
|
||||
|
||||
@@ -239,6 +239,7 @@
|
||||
"openchamber": "./bin/cli.js",
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.1.0",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@fontsource/ibm-plex-mono": "^5.2.7",
|
||||
@@ -534,6 +535,10 @@
|
||||
|
||||
"@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
|
||||
|
||||
"@clack/core": ["@clack/core@1.1.0", "", { "dependencies": { "sisteransi": "^1.0.5" } }, "sha512-SVcm4Dqm2ukn64/8Gub2wnlA5nS2iWJyCkdNHcvNHPIeBTGojpdJ+9cZKwLfmqy7irD4N5qLteSilJlE0WLAtA=="],
|
||||
|
||||
"@clack/prompts": ["@clack/prompts@1.1.0", "", { "dependencies": { "@clack/core": "1.1.0", "sisteransi": "^1.0.5" } }, "sha512-pkqbPGtohJAvm4Dphs2M8xE29ggupihHdy1x84HNojZuMtFsHiUlRvqD24tM2+XmI+61LlfNceM3Wr7U5QES5g=="],
|
||||
|
||||
"@codemirror/autocomplete": ["@codemirror/autocomplete@6.20.0", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-bOwvTOIJcG5FVo5gUUupiwYh8MioPLQ4UcqbcRf7UQ98X90tCa9E1kZ3Z7tqwpZxYyOvh1YTYbmZE9RTfTp5hg=="],
|
||||
|
||||
"@codemirror/commands": ["@codemirror/commands@6.10.2", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.4.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-vvX1fsih9HledO1c9zdotZYUZnE4xV0m6i3m25s5DIfXofuprk6cRcLUZvSk3CASUbwjQX21tOGbkY2BH8TpnQ=="],
|
||||
@@ -2624,6 +2629,8 @@
|
||||
|
||||
"simple-update-notifier": ["simple-update-notifier@2.0.0", "", { "dependencies": { "semver": "^7.5.3" } }, "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w=="],
|
||||
|
||||
"sisteransi": ["sisteransi@1.0.5", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="],
|
||||
|
||||
"slash": ["slash@2.0.0", "", {}, "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A=="],
|
||||
|
||||
"slice-ansi": ["slice-ansi@5.0.0", "", { "dependencies": { "ansi-styles": "^6.0.0", "is-fullwidth-code-point": "^4.0.0" } }, "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ=="],
|
||||
|
||||
@@ -25,8 +25,34 @@ Download from [Releases](https://github.com/btriapitsyn/openchamber/releases). A
|
||||
|
||||
Plus everything from the shared OpenChamber UI: branchable timeline, Git sidebar, terminal, voice mode, and more.
|
||||
|
||||
<details>
|
||||
<summary>Development</summary>
|
||||
## Features
|
||||
|
||||
### Core UI
|
||||
|
||||
- Branchable chat timeline with `/undo`, `/redo`, and one-click forks from earlier turns
|
||||
- Smart tool UIs for diffs, file operations, permissions, and long-running task progress
|
||||
- Multi-agent runs from one prompt with isolated worktrees for safe comparisons
|
||||
- Git workflows in-app: identities, commits, PR creation, checks, and merge actions
|
||||
- Context visibility tools (token/cost breakdowns, raw message inspection, and activity summaries)
|
||||
- Integrated terminal with per-directory sessions and stable performance on heavy output
|
||||
|
||||
### Desktop (macOS)
|
||||
|
||||
- Native macOS menu integration with polished app actions and deep-link handling
|
||||
- Multi-window support for parallel project/session workflows
|
||||
- "Open In" shortcuts for Finder, Terminal, and your preferred editor
|
||||
- Fast switching between local and remote instances
|
||||
- Workspace-first startup flow with directory picker and steadier window restore behavior
|
||||
|
||||
### Remote Tunnel (Desktop)
|
||||
|
||||
- Configure in **Settings -> OpenChamber -> Remote Tunnel**.
|
||||
- Supported Cloudflare modes: **Quick**, **Managed Remote**, **Managed Local**.
|
||||
- One active tunnel per Desktop instance. Starting a different mode replaces the current tunnel.
|
||||
- Replacing or stopping a tunnel revokes existing connect links and invalidates remote tunnel sessions.
|
||||
- Connect links are one-time tokens; generate a new link for each new connection attempt.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
git clone https://github.com/btriapitsyn/openchamber.git
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -29,7 +29,7 @@ export type SkillCatalogConfig = {
|
||||
gitIdentityId?: string;
|
||||
};
|
||||
|
||||
export type NamedTunnelPreset = {
|
||||
export type ManagedRemoteTunnelPreset = {
|
||||
id: string;
|
||||
name: string;
|
||||
hostname: string;
|
||||
@@ -94,15 +94,17 @@ export type DesktopSettings = {
|
||||
}>; // Per-provider custom model groups configuration
|
||||
autoDeleteEnabled?: boolean;
|
||||
autoDeleteAfterDays?: number;
|
||||
tunnelMode?: 'quick' | 'named';
|
||||
tunnelProvider?: string;
|
||||
tunnelMode?: 'quick' | 'managed-remote' | 'managed-local';
|
||||
tunnelBootstrapTtlMs?: number | null;
|
||||
tunnelSessionTtlMs?: number;
|
||||
namedTunnelHostname?: string;
|
||||
namedTunnelToken?: string | null;
|
||||
hasNamedTunnelToken?: boolean;
|
||||
namedTunnelPresets?: NamedTunnelPreset[];
|
||||
namedTunnelSelectedPresetId?: string;
|
||||
namedTunnelPresetTokens?: Record<string, string>;
|
||||
managedLocalTunnelConfigPath?: string | null;
|
||||
managedRemoteTunnelHostname?: string;
|
||||
managedRemoteTunnelToken?: string | null;
|
||||
hasManagedRemoteTunnelToken?: boolean;
|
||||
managedRemoteTunnelPresets?: ManagedRemoteTunnelPreset[];
|
||||
managedRemoteTunnelSelectedPresetId?: string;
|
||||
managedRemoteTunnelPresetTokens?: Record<string, string>;
|
||||
defaultModel?: string; // format: "provider/model"
|
||||
defaultVariant?: string;
|
||||
defaultAgent?: string;
|
||||
@@ -288,6 +290,31 @@ export const requestDirectoryAccess = async (
|
||||
return { success: true, path: directoryPath };
|
||||
};
|
||||
|
||||
export const requestFileAccess = async (
|
||||
options?: { filters?: Array<{ name: string; extensions: string[] }> }
|
||||
): Promise<{ success: boolean; path?: string; error?: string }> => {
|
||||
if (isTauriShell() && isDesktopLocalOriginActive()) {
|
||||
try {
|
||||
const tauri = (window as unknown as { __TAURI__?: TauriGlobal }).__TAURI__;
|
||||
const selected = await tauri?.dialog?.open?.({
|
||||
directory: false,
|
||||
multiple: false,
|
||||
title: 'Select File',
|
||||
...(options?.filters ? { filters: options.filters } : {}),
|
||||
});
|
||||
if (!selected || typeof selected !== 'string') {
|
||||
return { success: false, error: 'File selection cancelled' };
|
||||
}
|
||||
return { success: true, path: selected };
|
||||
} catch (error) {
|
||||
console.warn('Failed to request file access (tauri)', error);
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
|
||||
return { success: false, error: 'Native file picker not available' };
|
||||
};
|
||||
|
||||
export const startAccessingDirectory = async (
|
||||
directoryPath: string
|
||||
): Promise<{ success: boolean; error?: string }> => {
|
||||
|
||||
@@ -216,12 +216,12 @@ const sanitizeProjects = (value: unknown): DesktopSettings['projects'] | undefin
|
||||
return result.length > 0 ? result : undefined;
|
||||
};
|
||||
|
||||
const sanitizeNamedTunnelPresets = (value: unknown): DesktopSettings['namedTunnelPresets'] | undefined => {
|
||||
const sanitizeManagedRemoteTunnelPresets = (value: unknown): DesktopSettings['managedRemoteTunnelPresets'] | undefined => {
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const result: NonNullable<DesktopSettings['namedTunnelPresets']> = [];
|
||||
const result: NonNullable<DesktopSettings['managedRemoteTunnelPresets']> = [];
|
||||
const seenIds = new Set<string>();
|
||||
const seenHostnames = new Set<string>();
|
||||
|
||||
@@ -244,7 +244,7 @@ const sanitizeNamedTunnelPresets = (value: unknown): DesktopSettings['namedTunne
|
||||
return result;
|
||||
};
|
||||
|
||||
const sanitizeNamedTunnelPresetTokens = (value: unknown): DesktopSettings['namedTunnelPresetTokens'] | undefined => {
|
||||
const sanitizeManagedRemoteTunnelPresetTokens = (value: unknown): DesktopSettings['managedRemoteTunnelPresetTokens'] | undefined => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -512,9 +512,15 @@ const sanitizeWebSettings = (payload: unknown): DesktopSettings | null => {
|
||||
if (typeof candidate.autoDeleteAfterDays === 'number' && Number.isFinite(candidate.autoDeleteAfterDays)) {
|
||||
result.autoDeleteAfterDays = candidate.autoDeleteAfterDays;
|
||||
}
|
||||
if (typeof candidate.tunnelProvider === 'string') {
|
||||
const provider = candidate.tunnelProvider.trim().toLowerCase();
|
||||
if (provider.length > 0) {
|
||||
result.tunnelProvider = provider;
|
||||
}
|
||||
}
|
||||
if (typeof candidate.tunnelMode === 'string') {
|
||||
const mode = candidate.tunnelMode.trim().toLowerCase();
|
||||
if (mode === 'quick' || mode === 'named') {
|
||||
if (mode === 'quick' || mode === 'managed-remote' || mode === 'managed-local') {
|
||||
result.tunnelMode = mode;
|
||||
}
|
||||
}
|
||||
@@ -526,25 +532,31 @@ const sanitizeWebSettings = (payload: unknown): DesktopSettings | null => {
|
||||
if (typeof candidate.tunnelSessionTtlMs === 'number' && Number.isFinite(candidate.tunnelSessionTtlMs)) {
|
||||
result.tunnelSessionTtlMs = candidate.tunnelSessionTtlMs;
|
||||
}
|
||||
if (typeof candidate.namedTunnelHostname === 'string') {
|
||||
result.namedTunnelHostname = candidate.namedTunnelHostname.trim();
|
||||
if (candidate.managedLocalTunnelConfigPath === null) {
|
||||
result.managedLocalTunnelConfigPath = null;
|
||||
} else if (typeof candidate.managedLocalTunnelConfigPath === 'string') {
|
||||
const trimmed = candidate.managedLocalTunnelConfigPath.trim();
|
||||
result.managedLocalTunnelConfigPath = trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
if (candidate.namedTunnelToken === null) {
|
||||
result.namedTunnelToken = null;
|
||||
} else if (typeof candidate.namedTunnelToken === 'string') {
|
||||
result.namedTunnelToken = candidate.namedTunnelToken.trim();
|
||||
if (typeof candidate.managedRemoteTunnelHostname === 'string') {
|
||||
result.managedRemoteTunnelHostname = candidate.managedRemoteTunnelHostname.trim();
|
||||
}
|
||||
const namedTunnelPresets = sanitizeNamedTunnelPresets(candidate.namedTunnelPresets);
|
||||
if (namedTunnelPresets) {
|
||||
result.namedTunnelPresets = namedTunnelPresets;
|
||||
if (candidate.managedRemoteTunnelToken === null) {
|
||||
result.managedRemoteTunnelToken = null;
|
||||
} else if (typeof candidate.managedRemoteTunnelToken === 'string') {
|
||||
result.managedRemoteTunnelToken = candidate.managedRemoteTunnelToken.trim();
|
||||
}
|
||||
if (typeof candidate.namedTunnelSelectedPresetId === 'string') {
|
||||
const trimmed = candidate.namedTunnelSelectedPresetId.trim();
|
||||
result.namedTunnelSelectedPresetId = trimmed.length > 0 ? trimmed : undefined;
|
||||
const managedRemoteTunnelPresets = sanitizeManagedRemoteTunnelPresets(candidate.managedRemoteTunnelPresets);
|
||||
if (managedRemoteTunnelPresets) {
|
||||
result.managedRemoteTunnelPresets = managedRemoteTunnelPresets;
|
||||
}
|
||||
const namedTunnelPresetTokens = sanitizeNamedTunnelPresetTokens(candidate.namedTunnelPresetTokens);
|
||||
if (namedTunnelPresetTokens) {
|
||||
result.namedTunnelPresetTokens = namedTunnelPresetTokens;
|
||||
if (typeof candidate.managedRemoteTunnelSelectedPresetId === 'string') {
|
||||
const trimmed = candidate.managedRemoteTunnelSelectedPresetId.trim();
|
||||
result.managedRemoteTunnelSelectedPresetId = trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
const managedRemoteTunnelPresetTokens = sanitizeManagedRemoteTunnelPresetTokens(candidate.managedRemoteTunnelPresetTokens);
|
||||
if (managedRemoteTunnelPresetTokens) {
|
||||
result.managedRemoteTunnelPresetTokens = managedRemoteTunnelPresetTokens;
|
||||
}
|
||||
if (typeof candidate.defaultModel === 'string' && candidate.defaultModel.length > 0) {
|
||||
result.defaultModel = candidate.defaultModel;
|
||||
|
||||
+26
-40
@@ -21,48 +21,30 @@ Or install manually: `bun add -g @openchamber/web` (or npm, pnpm, yarn).
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
openchamber # Start on port 3000
|
||||
openchamber --port 8080 # Custom port
|
||||
openchamber --ui-password secret # Password-protect
|
||||
openchamber stop # Stop server
|
||||
openchamber update # Update to latest
|
||||
openchamber # Start on port 3000
|
||||
openchamber --port 8080 # Custom port
|
||||
openchamber --ui-password secret # Password-protect UI
|
||||
openchamber tunnel help # Tunnel lifecycle commands
|
||||
openchamber tunnel providers # Show provider capabilities
|
||||
openchamber tunnel profile add --provider cloudflare --mode managed-remote --name prod-main --hostname app.example.com --token <token>
|
||||
openchamber tunnel start --profile prod-main
|
||||
openchamber tunnel start --provider cloudflare --mode quick --qr
|
||||
openchamber tunnel start --provider cloudflare --mode managed-local --config ~/.cloudflared/config.yml
|
||||
openchamber tunnel status --all # Show tunnel state across instances
|
||||
openchamber tunnel stop --port 3000 # Stop tunnel only (server stays running)
|
||||
openchamber logs # Follow latest instance logs
|
||||
OPENCODE_PORT=4096 OPENCODE_SKIP_START=true openchamber # Connect to external OpenCode server
|
||||
OPENCODE_HOST=https://myhost:4096 OPENCODE_SKIP_START=true openchamber # Connect via custom host/HTTPS
|
||||
openchamber stop # Stop server
|
||||
openchamber update # Update to latest version
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Remote access & tunnels</summary>
|
||||
### Tunnel behavior notes
|
||||
|
||||
```bash
|
||||
openchamber --try-cf-tunnel # Cloudflare Quick Tunnel
|
||||
openchamber --try-cf-tunnel --tunnel-qr # + QR code for mobile
|
||||
openchamber --try-cf-tunnel --tunnel-password-url # + password in URL
|
||||
```
|
||||
|
||||
Named Tunnel mode is configured in-app at **Settings > OpenChamber > Tunnel**. Requires [cloudflared](https://github.com/cloudflare/cloudflared/releases).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Connect to external OpenCode server</summary>
|
||||
|
||||
```bash
|
||||
OPENCODE_PORT=4096 OPENCODE_SKIP_START=true openchamber
|
||||
OPENCODE_HOST=https://myhost:4096 OPENCODE_SKIP_START=true openchamber
|
||||
```
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `OPENCODE_HOST` | Full base URL of external server (overrides `OPENCODE_PORT`) |
|
||||
| `OPENCODE_PORT` | Port of external server |
|
||||
| `OPENCODE_SKIP_START` | Skip starting embedded OpenCode server |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Docker</summary>
|
||||
|
||||
```bash
|
||||
docker compose up -d # Available at http://localhost:3000
|
||||
```
|
||||
- One active tunnel per running OpenChamber instance (port).
|
||||
- Starting a different tunnel mode/provider on the same instance replaces the active tunnel.
|
||||
- Replacing or stopping a tunnel revokes existing connect links and invalidates remote tunnel sessions.
|
||||
- Connect links are one-time tokens; generating a new link revokes the previous unused link.
|
||||
|
||||
**Optional env vars:**
|
||||
```yaml
|
||||
@@ -97,7 +79,11 @@ openchamber stop # Stop background server
|
||||
- **Self-update** - update and restart from the UI, server settings stay intact
|
||||
- **Cross-tab tracking** - session activity stays in sync across browser tabs
|
||||
|
||||
Plus everything from the shared OpenChamber UI: branchable timeline, Git sidebar, terminal, voice mode, and more.
|
||||
- Cloudflare tunnel access with Quick, managed-remote, and managed-local modes
|
||||
- One-scan onboarding with tunnel QR + password URL helpers
|
||||
- Mobile-first experience: optimized chat controls, keyboard-safe layouts, and attachment-friendly UI
|
||||
- Background notifications plus reliable cross-tab session activity tracking
|
||||
- Built-in self-update + restart flow that keeps your server settings intact
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* CLI output formatting adapter.
|
||||
*
|
||||
* Wraps @clack/prompts for structured, beautiful terminal output.
|
||||
* Custom formatters (icons, redaction) live here to isolate the
|
||||
* formatting dependency from the rest of the CLI.
|
||||
*/
|
||||
|
||||
import {
|
||||
intro,
|
||||
outro,
|
||||
log,
|
||||
note,
|
||||
box,
|
||||
progress,
|
||||
spinner,
|
||||
confirm,
|
||||
select,
|
||||
text,
|
||||
password,
|
||||
cancel,
|
||||
isCancel,
|
||||
} from '@clack/prompts';
|
||||
|
||||
// ── Provider icons ──────────────────────────────────────────────
|
||||
|
||||
const TUNNEL_PROVIDER_ICON = {
|
||||
cloudflare: '☁',
|
||||
};
|
||||
|
||||
function formatProviderWithIcon(provider) {
|
||||
if (typeof provider !== 'string' || provider.trim().length === 0) {
|
||||
return 'unknown';
|
||||
}
|
||||
const normalized = provider.trim().toLowerCase();
|
||||
const icon = TUNNEL_PROVIDER_ICON[normalized];
|
||||
return icon ? `${icon} ${normalized}` : normalized;
|
||||
}
|
||||
|
||||
// ── Status-aware log dispatch ───────────────────────────────────
|
||||
|
||||
/**
|
||||
* Print a status-tagged message using clack log primitives.
|
||||
*
|
||||
* @param {'success'|'warning'|'error'|'info'|'neutral'} status
|
||||
* @param {string} message Primary line
|
||||
* @param {string} [detail] Optional dim secondary line appended after newline
|
||||
*/
|
||||
function logStatus(status, message, detail) {
|
||||
const full = detail ? `${message}\n${detail}` : message;
|
||||
switch (status) {
|
||||
case 'success':
|
||||
log.success(full);
|
||||
break;
|
||||
case 'warning':
|
||||
log.warn(full);
|
||||
break;
|
||||
case 'error':
|
||||
log.error(full);
|
||||
break;
|
||||
case 'info':
|
||||
case 'neutral':
|
||||
default:
|
||||
log.info(full);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── TTY detection ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Whether both stdout and stdin are interactive TTYs.
|
||||
* Prompts must be disabled when stdin is piped (e.g. --token-stdin).
|
||||
*/
|
||||
const isTTY = Boolean(process.stdout?.isTTY) && Boolean(process.stdin?.isTTY);
|
||||
|
||||
function isJsonMode(options) {
|
||||
return Boolean(options?.json);
|
||||
}
|
||||
|
||||
function isQuietMode(options) {
|
||||
return Boolean(options?.quiet);
|
||||
}
|
||||
|
||||
function shouldRenderHumanOutput(options) {
|
||||
return !isJsonMode(options) && !isQuietMode(options);
|
||||
}
|
||||
|
||||
function canPrompt(options) {
|
||||
return shouldRenderHumanOutput(options) && isTTY;
|
||||
}
|
||||
|
||||
function createSpinner(options) {
|
||||
return canPrompt(options) ? spinner() : null;
|
||||
}
|
||||
|
||||
async function createProgress(options, config) {
|
||||
return canPrompt(options) ? progress(config) : null;
|
||||
}
|
||||
|
||||
function printJson(payload) {
|
||||
const base = payload && typeof payload === 'object' && !Array.isArray(payload)
|
||||
? { ...payload }
|
||||
: { data: payload };
|
||||
|
||||
const messages = Array.isArray(base.messages) ? base.messages : undefined;
|
||||
const hasWarning = Boolean(messages?.some((entry) => entry?.level === 'warning'));
|
||||
const hasError = Boolean(messages?.some((entry) => entry?.level === 'error'));
|
||||
const normalizedStatus = base.status === 'ok' || base.status === 'warning' || base.status === 'error'
|
||||
? base.status
|
||||
: (hasError ? 'error' : (hasWarning ? 'warning' : 'ok'));
|
||||
|
||||
const output = {
|
||||
status: normalizedStatus,
|
||||
...base,
|
||||
};
|
||||
|
||||
process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
|
||||
}
|
||||
|
||||
export {
|
||||
intro,
|
||||
outro,
|
||||
log,
|
||||
note,
|
||||
box,
|
||||
progress,
|
||||
spinner,
|
||||
confirm,
|
||||
select,
|
||||
text,
|
||||
password,
|
||||
cancel,
|
||||
isCancel,
|
||||
isTTY,
|
||||
isJsonMode,
|
||||
isQuietMode,
|
||||
shouldRenderHumanOutput,
|
||||
canPrompt,
|
||||
createSpinner,
|
||||
createProgress,
|
||||
printJson,
|
||||
formatProviderWithIcon,
|
||||
logStatus,
|
||||
};
|
||||
Executable → Regular
+4330
-692
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,7 @@
|
||||
"start": "node bin/cli.js serve"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.1.0",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
"@codemirror/lang-go": "^6.0.1",
|
||||
"@fontsource/ibm-plex-mono": "^5.2.7",
|
||||
|
||||
Vendored
+10
-1
@@ -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;
|
||||
};
|
||||
|
||||
+798
-264
File diff suppressed because it is too large
Load Diff
@@ -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/
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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`);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user