@ghostlygawd/hangar 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,101 @@
1
+ # Changelog
2
+
3
+ All notable changes to Hangar are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.2.0] - 2026-06-13
11
+
12
+ ### Security
13
+
14
+ - **Token gate now covers the whole surface, not just `/api/*`.** With a token
15
+ set (LAN/tunnel), the dashboard shell and its assets were served unauthenticated —
16
+ a stranger could load the app and its client source. Everything except
17
+ `/api/health` is now gated. A correctly-linked phone still works: opening the
18
+ tunnel link once with `?token=…` sets an HttpOnly session cookie so subsequent
19
+ asset/document loads (which carry no query) pass.
20
+ - **`hangar tunnel` refuses to expose an ungated server.** Setting a token after
21
+ the server was already running left the live gate OFF while the tunnel opened —
22
+ open to the internet behind a URL that looked protected. `tunnel` now pushes the
23
+ token to the running server and proves a gated endpoint returns `401` before
24
+ opening cloudflared, and aborts otherwise.
25
+ - **`hangar config token ""` no longer silently disables the gate.** Empty/blank
26
+ tokens are rejected; turning the gate off is now an explicit
27
+ `hangar config token --clear`.
28
+
29
+ ### Fixed
30
+
31
+ - **Worktree safety (SACRED): `deleteSpace` could escape `.hangar-spaces`.** It
32
+ never validated the space name (unlike `createSpace`), so a crafted
33
+ `..\..\name` could resolve onto another worktree and run `git worktree remove` +
34
+ `git branch -d` on it. Delete now validates the name, asserts the target and the
35
+ matched worktree live strictly inside the repo's spaces root, and refuses any
36
+ worktree that has the default branch checked out.
37
+ - **Detached-HEAD spaces** now refuse deletion with a clear message instead of
38
+ `Branch "null" is not merged`.
39
+ - **A failed branch delete is surfaced** as a warning instead of reporting success.
40
+ - **Windows Terminal launch was broken on the default path.** Unescaped `;` made
41
+ `wt` split the command across tabs — `CLAUDE_CONFIG_DIR` set in one, `claude`
42
+ started in another (wrong account), or never started. The command is now passed
43
+ as a base64 `-EncodedCommand` blob `wt` cannot split.
44
+ - **SSE stream correctness.** The events handler never called `reply.hijack()`,
45
+ so Fastify 5 double-sent on every connection; `Bus.publish` had no per-client
46
+ isolation, so one dead phone tab could starve every other client and crash the
47
+ watchers; shutdown left SSE sockets and heartbeats open. All three fixed.
48
+ - **IPv6 loopback (`::1`)** is now treated as loopback by the LAN-bind guard
49
+ (no longer forces a token for a localhost-only bind).
50
+
51
+ ### Changed
52
+
53
+ - **The entire cockpit was rebuilt to a new design language, "Deep Ink"**
54
+ (`design/LANGUAGE.md` + `design/tokens.css`): a premium, restrained dark UI with
55
+ one reserved accent, a semantic status ramp, a real Lucide icon set (the cryptic
56
+ Unicode nav glyphs are gone), and a real mobile bottom-nav. The redesign folds in
57
+ the outstanding UI bugs: the **Session git-diff panel** that was missing entirely,
58
+ the mobile **"can't create a space"** overflow, the silent Launch (now a visible
59
+ idle→opening→waiting→live lifecycle), infinite-skeleton outages (one global
60
+ connection banner), markdown leaking into feeds, the raw process-table dump
61
+ (now session-centric, raw view behind a disclosure), and the Settings token
62
+ self-lockout.
63
+
64
+ ### Added
65
+
66
+ - **`hangar doctor`** — a first-run preflight that checks Node 18+, Claude Code on
67
+ PATH, and sign-in, naming exactly what's missing. Runs (non-blocking) on `hangar`
68
+ start so the first launch can't fail silently.
69
+ - **`hangar tunnel` prints a ready-to-use tokened link and a QR code** (via
70
+ `qrcode-terminal`, Apache-2.0, zero dependencies) — no more hand-splicing the
71
+ URL and token.
72
+ - **Design departments** as Claude Code skills (`.claude/skills/{ui,ux,
73
+ functionality,deployment}`) that enforce the design language, the hard rules, and
74
+ Keep-a-Changelog/SemVer on future work.
75
+ - **Tests for the safety-critical surfaces** that previously had none: the token
76
+ gate (open/closed/cookie/Bearer), the LAN-bind guard, the Windows Terminal launch
77
+ builder, the worktree-delete path (traversal + detached HEAD), and the doctor.
78
+ - **`test/e2e.test.js`** — an end-to-end harness that boots the real server and
79
+ drives the whole loop over HTTP with synthetic transcripts (never a headless
80
+ Claude): gate/SSE, repo→space→worktree, session-from-transcript, limit→park→
81
+ continue, and safe-delete. Suite: 27 → 51 tests.
82
+
83
+ ### Known issues
84
+
85
+ - The dev test toolchain (esbuild→vite→vitest) carries advisories fixable only by
86
+ a breaking `vitest` major bump; tracked separately. No shipped/runtime dependency
87
+ is affected.
88
+
89
+ ## [0.1.0] - 2026-06-13
90
+
91
+ ### Added
92
+
93
+ - Initial release: worktree **spaces** engine, real interactive session launch
94
+ (never headless), zero-token transcript observability, the cockpit UI,
95
+ multi-account profiles via `CLAUDE_CONFIG_DIR`, phone access (token gate + LAN +
96
+ cloudflared tunnel), structured-field limit detection, and the one-pager site.
97
+ Apache-2.0.
98
+
99
+ [Unreleased]: https://github.com/GhostlyGawd/hangar/compare/v0.2.0...HEAD
100
+ [0.2.0]: https://github.com/GhostlyGawd/hangar/compare/v0.1.0...v0.2.0
101
+ [0.1.0]: https://github.com/GhostlyGawd/hangar/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # Hangar
2
+
3
+ **A free, open-source cockpit for running Claude Code in parallel on Windows.**
4
+
5
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
6
+ [![Release](https://img.shields.io/github/v/release/GhostlyGawd/hangar?display_name=tag&sort=semver)](https://github.com/GhostlyGawd/hangar/releases/latest)
7
+ [![Tests](https://img.shields.io/badge/tests-42%20passing-34D399.svg)](#development)
8
+ [![Zero running cost](https://img.shields.io/badge/running%20cost-%240-34D399.svg)](#why-its-different)
9
+
10
+ Spin up isolated worktree **spaces** as fast as you can think of them, launch a **real interactive Claude Code window** in any of them — under whichever account has headroom — and watch everything from one dashboard, on desktop or your phone. Your main branch is structurally safe the whole time.
11
+
12
+ Think **Conductor, but Windows-native — and better.** Plus the feature nobody else ships: **multi-account**. When one subscription hits its weekly limit, Hangar parks it and one click continues the same space on your other account.
13
+
14
+ → **[ghostlygawd.github.io/hangar](https://ghostlygawd.github.io/hangar)**
15
+
16
+ ## Install
17
+
18
+ ### The easy way — download
19
+
20
+ Grab the latest **`Hangar.exe`** from **[Releases](https://github.com/GhostlyGawd/hangar/releases/latest)**, double-click it, and the cockpit opens in your browser. No terminal, no setup.
21
+
22
+ > The download is unsigned (a code-signing certificate costs money, and Hangar is committed to zero paid dependencies), so Windows SmartScreen shows a one-time prompt — click **More info → Run anyway**.
23
+
24
+ ### For developers — npm
25
+
26
+ If you live in a terminal:
27
+
28
+ ```powershell
29
+ npm i -g @ghostlygawd/hangar # or: npx @ghostlygawd/hangar
30
+ hangar # starts the cockpit and opens it in your browser
31
+ ```
32
+
33
+ You need [Node 18+](https://nodejs.org) and [Claude Code](https://docs.anthropic.com/en/docs/claude-code) — which, if you're here, you already have. Run `hangar doctor` anytime to confirm your setup.
34
+
35
+ Then: add a repo on the Board, create a space, hit **Launch**. That's the whole loop.
36
+
37
+ ## Why it's different
38
+
39
+ - **Real windows, never headless.** Hangar opens actual interactive `claude` terminals you can type in. Fan-out happens with subagents *inside* a session — not with opaque background fleets.
40
+ - **Zero-token observability.** The dashboard works by tailing the transcript files Claude Code already writes. Watching a session costs *nothing* — it uses exactly the tokens a hand-opened session would.
41
+ - **Zero running cost.** Localhost server, no cloud, no accounts, no telemetry. Optional free Cloudflare quick tunnel for phone access, gated by a timing-safe token.
42
+ - **Structurally safe parallelism.** A space is a git worktree on its own branch. Deleting one is only possible when it's merged + clean — anything else requires typing the space's name into a force-confirm. The default branch's checkout is untouchable.
43
+
44
+ ## The tour
45
+
46
+ | View | What it shows |
47
+ |---|---|
48
+ | **Board** | Every repo → its spaces as cards: branch, dirty/merged state, diff stat, the live launch lifecycle (opening → waiting → live), launch + safe-delete |
49
+ | **Activity** | The latest move in every session across all spaces, newest first |
50
+ | **System** | A session-centric health view (CPU / memory / network / disks), with the raw process list one click away — sampled only while you're watching |
51
+ | **Settings** | Account profiles, parked-limit status, remote-access token, tracked repos |
52
+
53
+ ## Multi-account in 3 commands
54
+
55
+ ```powershell
56
+ hangar login alt # opens a window for the "alt" profile — run /login inside it once
57
+ # …work normally; launch any space under any profile from the Board…
58
+ hangar tunnel # optional: watch from your phone — prints a tokened link + QR
59
+ ```
60
+
61
+ When a profile hits its limit, Hangar detects it from structured transcript fields (never by reading message text), shows a parked badge, and offers **continue as** on your other profile. It never switches automatically.
62
+
63
+ ## Docs
64
+
65
+ - [Getting started](docs/getting-started.md) — zero to first watched session in 5 minutes
66
+ - [How it works](docs/how-it-works.md) — spaces, profiles, transcript tailing, the safety rules
67
+ - [Configuration](docs/configuration.md) — every key in `~/.hangar/config.json`
68
+ - [Changelog](CHANGELOG.md) · [Contributing](CONTRIBUTING.md)
69
+
70
+ ## Development
71
+
72
+ ```powershell
73
+ git clone https://github.com/GhostlyGawd/hangar.git
74
+ cd hangar && npm install
75
+
76
+ npm test # core safety suite (worktree rules, gate, launch, limit detection)
77
+ npm run web:dev # frontend dev server with API proxy
78
+ npm run web:build # rebuild web/dist (committed)
79
+ node bin/hangar.js # run from source
80
+ ```
81
+
82
+ The design language lives in [`design/LANGUAGE.md`](design/LANGUAGE.md); the work is tracked on Linear and the kit's "department" conventions live in [`.claude/skills/`](.claude/skills).
83
+
84
+ ## License
85
+
86
+ [Apache-2.0](LICENSE). Built by [GhostlyGawd](https://github.com/GhostlyGawd). Not affiliated with Anthropic.
package/bin/hangar.js ADDED
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ import { spawn, execFile } from 'node:child_process'
3
+ import qrcode from 'qrcode-terminal'
4
+ import { startServer } from '../server/index.js'
5
+ import { JsonStore } from '../lib/store.js'
6
+ import { CONFIG_FILE, DEFAULT_CONFIG, claudeHomeFor } from '../lib/paths.js'
7
+ import { addProfile, listProfiles } from '../lib/profiles.js'
8
+ import { runDoctor, formatDoctor } from '../lib/doctor.js'
9
+
10
+ function parsePort(raw) {
11
+ const n = Number(raw)
12
+ if (!Number.isInteger(n) || n < 1 || n > 65535) fail('--port must be a whole number between 1 and 65535')
13
+ return n
14
+ }
15
+
16
+ const args = process.argv.slice(2)
17
+ const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'start'
18
+
19
+ const HELP = `hangar — parallel Claude Code cockpit
20
+
21
+ Usage:
22
+ hangar start the server and open the app
23
+ hangar doctor check your setup (Node, Claude Code, sign-in)
24
+ hangar login <profile> open an interactive window to log a profile in
25
+ hangar tunnel expose the running dashboard via a free cloudflared quick tunnel
26
+ hangar config token <val> set the access token (required for LAN/tunnel)
27
+ hangar config token --clear turn the access token off (localhost only)
28
+ hangar --help
29
+
30
+ Options for start:
31
+ --port <n> port (default 4870)
32
+ --lan bind 0.0.0.0 (requires a token)
33
+ --no-open don't open the browser
34
+ `
35
+
36
+ function flag(name) { return args.includes(name) }
37
+ function opt(name) {
38
+ const i = args.indexOf(name)
39
+ return i !== -1 ? args[i + 1] : undefined
40
+ }
41
+
42
+ function fail(msg) {
43
+ console.error(`hangar: ${msg}`)
44
+ process.exit(1)
45
+ }
46
+
47
+ async function main() {
48
+ if (process.platform !== 'win32' && !flag('--help') && cmd !== 'help') {
49
+ fail('Hangar is Windows-only for now — it drives PowerShell and Windows Terminal. Track cross-platform support at https://github.com/GhostlyGawd/hangar')
50
+ }
51
+ try {
52
+ if (flag('--help') || cmd === 'help') {
53
+ console.log(HELP)
54
+ } else if (cmd === 'start') {
55
+ const overrides = {}
56
+ if (opt('--port')) overrides.port = parsePort(opt('--port'))
57
+ if (flag('--lan')) overrides.bind = '0.0.0.0'
58
+ const { port, bind } = await startServer(overrides)
59
+ const url = `http://${bind === '0.0.0.0' ? 'localhost' : bind}:${port}`
60
+ console.log(`hangar is up: ${url}`)
61
+ // non-blocking preflight — warn (never block) if the setup can't launch sessions
62
+ const report = formatDoctor(await runDoctor())
63
+ if (!report.ok || report.text.includes('⚠')) {
64
+ console.log(`\nPreflight (run \`hangar doctor\` for details):\n${report.text}`)
65
+ }
66
+ if (!flag('--no-open')) {
67
+ spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' }).unref()
68
+ }
69
+ } else if (cmd === 'login') {
70
+ const name = args[1]
71
+ if (!name) fail('usage: hangar login <profile>')
72
+ if (name !== 'default') {
73
+ const res = addProfile(name)
74
+ if (!res.ok) fail(res.error)
75
+ }
76
+ const home = claudeHomeFor(name)
77
+ console.log(`Opening an interactive window for profile "${name}" (${home}).`)
78
+ console.log(`If this account isn't logged in yet, run /login inside it.`)
79
+ const inner = name === 'default'
80
+ ? 'claude'
81
+ : `$env:CLAUDE_CONFIG_DIR='${home.replace(/'/g, "''")}'; claude`
82
+ spawn('powershell', ['-NoProfile', '-Command',
83
+ `Start-Process powershell -ArgumentList @('-NoExit','-NoProfile','-ExecutionPolicy','Bypass','-Command','${inner.replace(/'/g, "''")}')`,
84
+ ], { detached: true, stdio: 'ignore' }).unref()
85
+ } else if (cmd === 'tunnel') {
86
+ const config = new JsonStore(CONFIG_FILE, DEFAULT_CONFIG)
87
+ const token = config.data.token
88
+ if (!token) fail('set a token first: hangar config token <value>')
89
+ const port = opt('--port') ? parsePort(opt('--port')) : config.data.port
90
+ const origin = `http://127.0.0.1:${port}`
91
+
92
+ // 1) a server must actually be running on this port
93
+ const health = await fetch(`${origin}/api/health`).catch(() => null)
94
+ if (!health?.ok) fail(`no Hangar server is answering on ${origin}. Start it first (hangar --port ${port}), then tunnel.`)
95
+
96
+ // 2) push the token to the LIVE server so its gate is on, then PROVE it's gated
97
+ // before exposing anything — a running server started without a token would
98
+ // otherwise be put on the internet wide open.
99
+ await fetch(`${origin}/api/config?token=${encodeURIComponent(token)}`, {
100
+ method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ token }),
101
+ }).catch(() => null)
102
+ const probe = await fetch(`${origin}/api/state`).catch(() => null)
103
+ if (probe?.status !== 401) {
104
+ fail('refusing to open a tunnel: the running server is not gated. Restart it after setting the token so it picks the token up, then tunnel again.')
105
+ }
106
+
107
+ // 3) cloudflared present, then announce the ready-to-use tokened link + QR
108
+ execFile('where.exe', ['cloudflared'], (err) => {
109
+ if (err) fail('cloudflared not found. Install it free: winget install Cloudflare.cloudflared')
110
+ console.log('Starting a free cloudflared tunnel (Ctrl+C stops it)…\n')
111
+ const t = spawn('cloudflared', ['tunnel', '--url', origin], { stdio: ['ignore', 'pipe', 'pipe'] })
112
+ let announced = false
113
+ const onChunk = (buf) => {
114
+ const text = buf.toString()
115
+ process.stdout.write(text)
116
+ const m = !announced && text.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/i)
117
+ if (m) {
118
+ announced = true
119
+ const link = `${m[0]}/?token=${encodeURIComponent(token)}`
120
+ console.log(`\n Open this on your phone (token included — just scan or tap):\n ${link}\n`)
121
+ qrcode.generate(link, { small: true })
122
+ }
123
+ }
124
+ t.stdout.on('data', onChunk)
125
+ t.stderr.on('data', onChunk)
126
+ t.on('exit', (code) => process.exit(code ?? 0))
127
+ })
128
+ } else if (cmd === 'config') {
129
+ const [, key, value] = args
130
+ if (key !== 'token') fail('usage: hangar config token <value> (or: hangar config token --clear)')
131
+ const config = new JsonStore(CONFIG_FILE, DEFAULT_CONFIG)
132
+ if (value === '--clear') {
133
+ config.update((d) => { d.token = '' })
134
+ console.log('token cleared — the gate is now OFF (localhost only).')
135
+ } else if (value === undefined || value.trim() === '') {
136
+ fail('token cannot be empty. To turn the gate off: hangar config token --clear')
137
+ } else {
138
+ config.update((d) => { d.token = value })
139
+ console.log('token set.')
140
+ }
141
+ } else if (cmd === 'doctor') {
142
+ const report = formatDoctor(await runDoctor())
143
+ console.log(`hangar doctor\n${report.text}\n`)
144
+ console.log(report.ok ? 'Ready to fly.' : 'Fix the ✗ items above, then run `hangar`.')
145
+ if (!report.ok) process.exit(1)
146
+ } else if (cmd === 'profiles') {
147
+ for (const p of listProfiles()) console.log(`${p.name}${p.implicit ? ' (default)' : ''}`)
148
+ } else {
149
+ fail(`unknown command "${cmd}". Try: hangar --help`)
150
+ }
151
+ } catch (err) {
152
+ fail(err.message)
153
+ }
154
+ }
155
+
156
+ main()
package/lib/doctor.js ADDED
@@ -0,0 +1,68 @@
1
+ import { execFile } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { defaultClaudeHome } from './paths.js'
5
+
6
+ /** Resolve a command on PATH (null if absent). Windows uses where.exe. */
7
+ function which(cmd) {
8
+ const finder = process.platform === 'win32' ? 'where.exe' : 'which'
9
+ return new Promise((resolve) => {
10
+ execFile(finder, [cmd], { windowsHide: true }, (err, stdout) => {
11
+ const first = String(stdout).split(/\r?\n/)[0]?.trim()
12
+ resolve(err || !first ? null : first)
13
+ })
14
+ })
15
+ }
16
+
17
+ /**
18
+ * Preflight checks so the first launch can't fail silently.
19
+ * Returns [{ name, ok, level, detail, fix }]. level: 'error' blocks launches,
20
+ * 'warn' is advisory. We never READ credentials — only test for their presence
21
+ * (the hard rule forbids reading .credentials.json, not knowing it exists).
22
+ */
23
+ export async function runDoctor() {
24
+ const checks = []
25
+
26
+ const major = Number(process.versions.node.split('.')[0])
27
+ checks.push({
28
+ name: 'Node.js 18+',
29
+ ok: major >= 18,
30
+ level: 'error',
31
+ detail: `found v${process.versions.node}`,
32
+ fix: 'Install Node 18 or newer from https://nodejs.org',
33
+ })
34
+
35
+ const claudePath = await which('claude')
36
+ checks.push({
37
+ name: 'Claude Code on PATH',
38
+ ok: !!claudePath,
39
+ level: 'error',
40
+ detail: claudePath || 'not found',
41
+ fix: 'Install Claude Code and make sure `claude` runs in a new terminal — Hangar launches it directly.',
42
+ })
43
+
44
+ // Logged-in is advisory: some setups store auth in the OS keychain with no
45
+ // file, so a missing file is "couldn't confirm", not a hard failure.
46
+ const credFile = path.join(defaultClaudeHome(), '.credentials.json')
47
+ const credsPresent = fs.existsSync(credFile)
48
+ checks.push({
49
+ name: 'Default account signed in',
50
+ ok: credsPresent,
51
+ level: 'warn',
52
+ detail: credsPresent ? 'credentials present' : 'could not confirm',
53
+ fix: 'Run `hangar login default` (or `claude` once) and complete /login. Ignore if you signed in via keychain.',
54
+ })
55
+
56
+ return checks
57
+ }
58
+
59
+ /** Pretty one-screen report. Returns true if no error-level check failed. */
60
+ export function formatDoctor(checks) {
61
+ const mark = (c) => (c.ok ? '✓' : c.level === 'warn' ? '⚠' : '✗')
62
+ const lines = checks.map((c) => {
63
+ const head = ` ${mark(c)} ${c.name} — ${c.detail}`
64
+ return c.ok ? head : `${head}\n → ${c.fix}`
65
+ })
66
+ const blocking = checks.some((c) => !c.ok && c.level === 'error')
67
+ return { text: lines.join('\n'), ok: !blocking }
68
+ }