hermesdesk-agent 0.1.0-alpha.1 → 0.1.0-alpha.3

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![CI](https://github.com/NKocur/hermesdesk-agent/actions/workflows/ci.yml/badge.svg)](https://github.com/NKocur/hermesdesk-agent/actions/workflows/ci.yml)
4
4
 
5
- **Windows alpha: 0.1.0-alpha.1.** Community client built on Pi; not affiliated with or endorsed by Earendil Works or Nous Research.
5
+ **Windows alpha: 0.1.0-alpha.3.** Community client built on Pi; not affiliated with or endorsed by Earendil Works or Nous Research.
6
6
 
7
7
  A running HermesDesk inference gateway is required. This client does not include a hosted model service, server access, or API keys.
8
8
 
@@ -10,15 +10,21 @@ An initial Windows-first coding CLI built on the pinned Pi 1.5.0 SDK. The model
10
10
 
11
11
  ## Install on a Windows computer
12
12
 
13
- Install Node.js 22.19 or newer (Node 24 recommended). Download and extract a Windows alpha bundle from [Releases](https://github.com/NKocur/hermesdesk-agent/releases), then run `Install Agent.cmd`, or install the supplied package:
13
+ Install Node.js 22.19 or newer (Node 24 recommended), then install the alpha from npm:
14
14
 
15
15
  ```powershell
16
- npm.cmd install -g --ignore-scripts "C:\path\to\hermesdesk-agent-0.1.0-alpha.1.tgz"
16
+ npm.cmd install -g --ignore-scripts hermesdesk-agent@alpha
17
17
  hermesdesk.cmd connect
18
18
  hermesdesk.cmd doctor
19
19
  ```
20
20
 
21
- There is no default server address. `connect` asks for your HTTPS inference endpoint ending in `/v1`; for a server on this computer, loopback HTTP is also accepted. Enter a per-computer inference API key created in HermesDesk Settings > Connect coding tools. Use the Hermes/OpenAI-compatible key option; all current inference keys work with this client. The model is discovered automatically if the configured ID is unavailable. No keys are included in the package.
21
+ Alternatively, download and extract a Windows alpha bundle from [Releases](https://github.com/NKocur/hermesdesk-agent/releases) and run `Install Agent.cmd`. A tarball can also be installed directly with `npm.cmd install -g --ignore-scripts ./hermesdesk-agent-0.1.0-alpha.3.tgz`.
22
+
23
+ There is no default server address. `connect` asks for your HTTPS model endpoint ending in `/v1`. When the server supports browser sign-in, it opens your browser: sign in to HermesDesk and approve the computer. The CLI receives a short-lived, single-use authorization code on a loopback listener and redeems it with PKCE over HTTPS, then discovers the model and saves the credentials encrypted. You do not copy passwords, API keys, or connection codes. The browser and CLI must be on the same computer. Use `--no-browser` to open the printed browser link yourself. On legacy servers without browser sign-in, the API-key setup remains available; `--manual` explicitly selects it. No server credentials are included in this package.
24
+
25
+ For optional manual connection-code setup, select **HermesDesk Agent** in the server's **Connect coding tools** settings and create a connection. Run `hermesdesk.cmd connect --code`, then paste its private connection code at the hidden prompt. The code contains both model and Cloudflare Access credentials: treat it like a password. It is never passed as a command-line argument or saved in plain text. The server's normal key expiry and revocation still apply. The package also provides `hermesdesk-agent` as an alias for `hermesdesk`.
26
+
27
+ Manual Access setup is available with `hermesdesk connect --url https://your-worker.example/v1 --cloudflare-access`; all credentials are prompted privately. For session-only authentication, set `HERMESDESK_API_KEY`, `HERMESDESK_ACCESS_CLIENT_ID` and `HERMESDESK_ACCESS_CLIENT_SECRET`. Non-interactive setup on Windows can use `HERMESDESK_CONNECTION_CODE` with `connect --code`. The agent clears these variables before launching coding tools. Saved Access credentials are bound to the endpoint and removed by logout along with the model key.
22
28
 
23
29
  On Windows, saved keys are encrypted using DPAPI for the signed-in Windows user and bound to the configured endpoint. Configuration and sessions are stored under `%LOCALAPPDATA%\HermesDeskAgent`. The key is not written to Pi's auth JSON or passed on a command line. `HERMESDESK_API_KEY` supports session-only authentication; the client removes it from its environment before coding tools run. `hermesdesk logout` deletes the saved credential, but does not revoke it on the server.
24
30
 
@@ -64,7 +70,11 @@ hermesdesk.cmd config set maxRequests 64
64
70
 
65
71
  Changes apply to the next launch. Context is client metadata, not a request to allocate more server context: keep it at or below the server's configured capacity. Output is capped at 8192 by the gateway. The default request budget is 64 per message and can be set from 1 to 512. Pi's in-chat settings are session-only in this version. Change the server using `hermesdesk connect --url https://your-server/v1`. HTTP is accepted only on loopback addresses.
66
72
 
67
- Windows uses its built-in `curl.exe` for model HTTP requests because the retained Cloudflare bot filter challenged Node fetch and a native Node follow-up request during testing. TLS verification stays enabled, redirects are not followed, credentials are sent through stdin rather than command-line arguments, and disconnects cancel the request. `doctor` checks the connection without loading the model. Cold Strata startup can still take minutes; the client cannot remove server warm-up costs. A Cloudflare 403 is a connection failure, not a model error.
73
+ Windows uses its built-in `curl.exe` for model HTTP requests because the retained Cloudflare bot filter challenged Node fetch and a native Node follow-up request during testing. TLS verification stays enabled, redirects are not followed, credentials are sent through stdin rather than command-line arguments, and disconnects cancel the request. `doctor` checks the connection without loading the model. A browser challenge from zone-wide Bot Fight Mode cannot be solved by an API client; the server owner must configure API-compatible protection. Transport compatibility alone does not guarantee that every computer will be accepted. Cold Strata startup can still take minutes; the client cannot remove server warm-up costs. A Cloudflare 403 is a connection failure, not a model error.
74
+
75
+ ## Optional private Worker gateway
76
+
77
+ The generic Worker source and deployment notes are in [worker/](worker/README.md). It requires Cloudflare Access authentication for its configured application and proxies only model discovery and chat completions to a single private VPC Service. It exposes no desktop tools, file APIs, application sessions, or arbitrary destinations. Website Bot Fight Mode can remain enabled when the agent uses a separate `workers.dev` endpoint. Workers VPC is beta; check Cloudflare's current availability, pricing and limits before adopting it.
68
78
 
69
79
  ## Develop
70
80
 
package/bin/hermesdesk.js CHANGED
@@ -5,6 +5,7 @@ import readline from "node:readline/promises";
5
5
  import { parseArgs } from "node:util";
6
6
  import {
7
7
  VERSION,
8
+ supportedNode,
8
9
  configHome,
9
10
  loadConfig,
10
11
  saveConfig,
@@ -12,15 +13,31 @@ import {
12
13
  projectSessionDir,
13
14
  } from "../src/config.js";
14
15
  import {
15
- getCredential,
16
+ getConnection,
16
17
  saveCredential,
17
18
  hiddenInput,
18
19
  logout,
19
20
  } from "../src/credentials.js";
21
+ import { browserLogin } from "../src/browser-login.js";
22
+ import { parseConnectionCode, validateAccess } from "../src/connection.js";
23
+ const privateValues = new Set();
24
+ const protect = (value) => {
25
+ if (value) privateValues.add(value);
26
+ return value;
27
+ };
28
+ const clearAuthEnv = () => {
29
+ for (const key of [
30
+ "HERMESDESK_API_KEY",
31
+ "HERMESDESK_ACCESS_CLIENT_ID",
32
+ "HERMESDESK_ACCESS_CLIENT_SECRET",
33
+ "HERMESDESK_CONNECTION_CODE",
34
+ ])
35
+ delete process.env[key];
36
+ };
20
37
  import { discover } from "../src/transport.js";
21
38
  const help = `HermesDesk Agent ${VERSION} (Pi-based, Windows first)
22
39
 
23
- hermesdesk connect [--url https://your-server.example/v1]
40
+ hermesdesk connect [--code | --url https://your-server.example/v1] [--manual | --cloudflare-access]
24
41
  hermesdesk doctor
25
42
  hermesdesk chat [--cwd PATH] [--continue | --session ID] [--read-only]
26
43
  hermesdesk run "REQUEST" [--cwd PATH] [--json] [--read-only]
@@ -38,6 +55,10 @@ async function main() {
38
55
  allowPositionals: true,
39
56
  options: {
40
57
  url: { type: "string" },
58
+ code: { type: "boolean" },
59
+ manual: { type: "boolean" },
60
+ "no-browser": { type: "boolean" },
61
+ "cloudflare-access": { type: "boolean" },
41
62
  cwd: { type: "string" },
42
63
  session: { type: "string" },
43
64
  continue: { type: "boolean" },
@@ -56,17 +77,40 @@ async function main() {
56
77
  console.log(VERSION);
57
78
  return;
58
79
  }
80
+ if (!supportedNode())
81
+ throw Error(
82
+ "Node.js " +
83
+ process.versions.node +
84
+ " is too old. Install Node.js 24 (minimum supported: 22.19.0), close this terminal and open a new one, then run node --version before trying again.",
85
+ );
59
86
  const command = p.shift() || "chat",
60
87
  home = configHome();
61
88
  process.env.PI_CODING_AGENT_DIR = path.join(home, "pi");
62
89
  let config = loadConfig(home);
63
90
  if (command === "connect") {
91
+ let imported;
92
+ if (v.code || process.env.HERMESDESK_CONNECTION_CODE) {
93
+ if (v.url || v["cloudflare-access"])
94
+ throw Error(
95
+ "Use --code on its own; the private code includes the endpoint and credentials.",
96
+ );
97
+ imported = parseConnectionCode(
98
+ protect(
99
+ process.env.HERMESDESK_CONNECTION_CODE ||
100
+ (await hiddenInput(
101
+ "Private HermesDesk connection code (hidden): ",
102
+ )),
103
+ ),
104
+ );
105
+ config = validateConfig({ ...config, baseUrl: imported.baseUrl });
106
+ console.log("Connecting to " + config.baseUrl);
107
+ }
64
108
  if (v.url) config = validateConfig({ ...config, baseUrl: v.url });
65
109
  const rl = readline.createInterface({
66
110
  input: process.stdin,
67
111
  output: process.stdout,
68
112
  });
69
- if (!v.url && process.stdin.isTTY) {
113
+ if (!imported && !v.url && process.stdin.isTTY) {
70
114
  const answer = await rl.question(
71
115
  config.baseUrl
72
116
  ? "Server [" + config.baseUrl + "]: "
@@ -80,13 +124,44 @@ async function main() {
80
124
  throw Error(
81
125
  "Enter your server URL, or use hermesdesk connect --url https://your-server.example/v1.",
82
126
  );
83
- const token =
84
- process.env.HERMESDESK_API_KEY ||
85
- (await hiddenInput("HermesDesk API key (hidden): "));
86
- const models = await discover(config, token);
127
+ if (
128
+ !imported &&
129
+ !v.manual &&
130
+ !v["cloudflare-access"] &&
131
+ !process.env.HERMESDESK_API_KEY &&
132
+ !process.env.HERMESDESK_ACCESS_CLIENT_ID
133
+ ) {
134
+ imported = await browserLogin(config.baseUrl, {
135
+ launch: v["no-browser"] ? async () => {} : undefined,
136
+ });
137
+ }
138
+ const token = protect(
139
+ imported?.token ||
140
+ process.env.HERMESDESK_API_KEY ||
141
+ (await hiddenInput("HermesDesk API key (hidden): ")),
142
+ );
143
+ let access = imported?.access;
144
+ if (
145
+ !access &&
146
+ (v["cloudflare-access"] ||
147
+ process.env.HERMESDESK_ACCESS_CLIENT_ID ||
148
+ process.env.HERMESDESK_ACCESS_CLIENT_SECRET)
149
+ ) {
150
+ access = validateAccess({
151
+ clientId:
152
+ process.env.HERMESDESK_ACCESS_CLIENT_ID ||
153
+ (await hiddenInput("Cloudflare Access client ID (hidden): ")),
154
+ clientSecret:
155
+ process.env.HERMESDESK_ACCESS_CLIENT_SECRET ||
156
+ (await hiddenInput("Cloudflare Access client secret (hidden): ")),
157
+ });
158
+ }
159
+ protect(access?.clientSecret);
160
+ clearAuthEnv();
161
+ const models = await discover(config, token, access);
87
162
  if (!models.length) throw Error("No models are available.");
88
163
  if (!models.includes(config.model)) config.model = models[0];
89
- await saveCredential(home, config.baseUrl, token);
164
+ await saveCredential(home, config.baseUrl, token, access);
90
165
  saveConfig(config, home);
91
166
  console.log(
92
167
  "Connected. Credential protected for your Windows account.\nModel: " +
@@ -151,10 +226,12 @@ async function main() {
151
226
  throw Error("Unknown command. Use hermesdesk --help.");
152
227
  if (!config.baseUrl || !config.model)
153
228
  throw Error("Not connected. Run hermesdesk connect first.");
154
- const token = await getCredential(home, config.baseUrl);
155
- delete process.env.HERMESDESK_API_KEY;
229
+ const { token, access } = await getConnection(home, config.baseUrl);
230
+ protect(token);
231
+ protect(access?.clientSecret);
232
+ clearAuthEnv();
156
233
  if (command === "doctor") {
157
- const models = await discover(config, token);
234
+ const models = await discover(config, token, access);
158
235
  console.log(
159
236
  JSON.stringify(
160
237
  {
@@ -186,6 +263,7 @@ async function main() {
186
263
  config,
187
264
  home,
188
265
  token,
266
+ access,
189
267
  cwd,
190
268
  readOnly: !!v["read-only"],
191
269
  approveWrites: !!v["approve-writes"],
@@ -216,7 +294,12 @@ async function main() {
216
294
  }
217
295
  main().catch((e) => {
218
296
  let message = e.message || "Operation failed.";
219
- for (const secret of [process.env.HERMESDESK_API_KEY])
297
+ for (const secret of [
298
+ ...privateValues,
299
+ process.env.HERMESDESK_API_KEY,
300
+ process.env.HERMESDESK_ACCESS_CLIENT_SECRET,
301
+ process.env.HERMESDESK_CONNECTION_CODE,
302
+ ])
220
303
  if (secret) message = message.split(secret).join("[redacted]");
221
304
  if (/<!doctype|<html/i.test(message))
222
305
  message =
@@ -1,18 +1,19 @@
1
1
  {
2
2
  "name": "hermesdesk-agent",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "hermesdesk-agent",
9
- "version": "0.1.0-alpha.1",
9
+ "version": "0.1.0-alpha.3",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/pi-coding-agent": "1.5.0"
13
13
  },
14
14
  "bin": {
15
- "hermesdesk": "bin/hermesdesk.js"
15
+ "hermesdesk": "bin/hermesdesk.js",
16
+ "hermesdesk-agent": "bin/hermesdesk.js"
16
17
  },
17
18
  "devDependencies": {
18
19
  "prettier": "3.6.2"
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "hermesdesk-agent",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "Pi-based terminal coding client for HermesDesk and Strata",
5
5
  "type": "module",
6
6
  "bin": {
7
- "hermesdesk": "bin/hermesdesk.js"
7
+ "hermesdesk": "bin/hermesdesk.js",
8
+ "hermesdesk-agent": "bin/hermesdesk.js"
8
9
  },
9
10
  "engines": {
10
11
  "node": ">=22.19.0"
package/src/agent.js CHANGED
@@ -8,6 +8,7 @@ export async function createRuntime({
8
8
  config,
9
9
  home,
10
10
  token,
11
+ access,
11
12
  cwd = process.cwd(),
12
13
  readOnly = false,
13
14
  approveWrites = false,
@@ -39,7 +40,7 @@ export async function createRuntime({
39
40
  allowModelNetwork: false,
40
41
  refreshOnCreate: false,
41
42
  });
42
- const safeFetch = modelFetch(config.baseUrl);
43
+ const safeFetch = modelFetch(config.baseUrl, access);
43
44
  let requestCount = 0;
44
45
  modelRuntime.registerProvider("hermesdesk", {
45
46
  name: "HermesDesk / Strata",
@@ -0,0 +1,251 @@
1
+ import http from "node:http";
2
+ import crypto from "node:crypto";
3
+ import os from "node:os";
4
+ import { spawn } from "node:child_process";
5
+ import { endpoint } from "./config.js";
6
+ import { parseConnectionCode } from "./connection.js";
7
+ import { curlFetch, nativeFetch } from "./transport.js";
8
+ async function json(response) {
9
+ const reader = response.body?.getReader();
10
+ let text = "",
11
+ size = 0;
12
+ if (!reader) throw Error("Sign-in returned no response.");
13
+ for (;;) {
14
+ const { value, done } = await reader.read();
15
+ if (done) break;
16
+ size += value.length;
17
+ if (size > 16384) {
18
+ await reader.cancel();
19
+ throw Error("Invalid sign-in response.");
20
+ }
21
+ text += new TextDecoder().decode(value);
22
+ }
23
+ try {
24
+ return JSON.parse(text);
25
+ } catch {
26
+ throw Error("Invalid sign-in response.");
27
+ }
28
+ }
29
+ export function browserMetadata(baseUrl, data) {
30
+ const base = new URL(endpoint(baseUrl));
31
+ let auth, token;
32
+ try {
33
+ auth = new URL(data.authorization_url);
34
+ token = new URL(data.token_endpoint);
35
+ } catch {
36
+ throw Error("The server returned invalid browser sign-in settings.");
37
+ }
38
+ const local =
39
+ base.protocol === "http:" &&
40
+ ["127.0.0.1", "localhost"].includes(base.hostname);
41
+ if (
42
+ data.version !== 1 ||
43
+ auth.username ||
44
+ auth.password ||
45
+ auth.hash ||
46
+ !(
47
+ auth.protocol === "https:" ||
48
+ (local && auth.protocol === "http:" && auth.hostname === "127.0.0.1")
49
+ ) ||
50
+ token.origin !== base.origin ||
51
+ token.pathname !== "/auth/token" ||
52
+ token.search ||
53
+ token.hash ||
54
+ token.username ||
55
+ token.password
56
+ )
57
+ throw Error("The server returned unsafe browser sign-in settings.");
58
+ return { authorization: auth, token };
59
+ }
60
+ export async function openBrowser(url) {
61
+ const [command, args] =
62
+ process.platform === "win32"
63
+ ? ["rundll32.exe", ["url.dll,FileProtocolHandler", url]]
64
+ : process.platform === "darwin"
65
+ ? ["open", [url]]
66
+ : ["xdg-open", [url]];
67
+ await new Promise((resolve, reject) => {
68
+ const child = spawn(command, args, {
69
+ windowsHide: true,
70
+ stdio: "ignore",
71
+ detached: true,
72
+ });
73
+ child.once("error", reject);
74
+ child.once("spawn", () => {
75
+ child.unref();
76
+ resolve();
77
+ });
78
+ });
79
+ }
80
+ export async function browserLogin(
81
+ baseUrl,
82
+ {
83
+ launch = openBrowser,
84
+ log = console.log,
85
+ timeoutMs = 300000,
86
+ transport = process.platform === "win32" ? curlFetch : nativeFetch,
87
+ } = {},
88
+ ) {
89
+ const base = new URL(endpoint(baseUrl));
90
+ const info = await transport(base.origin + "/auth/info", {
91
+ headers: { "User-Agent": "HermesDesk-CLI/1.0" },
92
+ signal: AbortSignal.timeout(20000),
93
+ });
94
+ if (info.status === 404) {
95
+ await info.body?.cancel();
96
+ return null;
97
+ }
98
+ if (info.status !== 200) {
99
+ await info.body?.cancel();
100
+ throw Error(
101
+ "Browser sign-in is unavailable at this endpoint. Check the server address or use connect --code.",
102
+ );
103
+ }
104
+ const metadata = browserMetadata(baseUrl, await json(info));
105
+ const state = crypto.randomBytes(32).toString("base64url"),
106
+ verifier = crypto.randomBytes(32).toString("base64url"),
107
+ challenge = crypto
108
+ .createHash("sha256")
109
+ .update(verifier)
110
+ .digest("base64url");
111
+ let resolveCallback,
112
+ rejectCallback,
113
+ settled = false,
114
+ callbackResponse;
115
+ const callback = new Promise((resolve, reject) => {
116
+ resolveCallback = resolve;
117
+ rejectCallback = reject;
118
+ });
119
+ const server = http.createServer((req, res) => {
120
+ const fail = () => {
121
+ res.writeHead(400, {
122
+ "content-type": "text/plain",
123
+ "cache-control": "no-store",
124
+ connection: "close",
125
+ });
126
+ res.end("Invalid sign-in callback. Return to your terminal.");
127
+ };
128
+ if (
129
+ settled ||
130
+ req.method !== "GET" ||
131
+ !["127.0.0.1", "::ffff:127.0.0.1"].includes(req.socket.remoteAddress) ||
132
+ req.headers.host !== "127.0.0.1:" + server.address().port ||
133
+ req.url.length > 2048
134
+ )
135
+ return fail();
136
+ let u;
137
+ try {
138
+ u = new URL(req.url, "http://127.0.0.1");
139
+ } catch {
140
+ return fail();
141
+ }
142
+ const denied =
143
+ u.searchParams.getAll("error").length === 1 &&
144
+ u.searchParams.get("error") === "access_denied" &&
145
+ !u.searchParams.has("code");
146
+ const validCode =
147
+ !u.searchParams.has("error") &&
148
+ u.searchParams.getAll("code").length === 1 &&
149
+ /^[A-Za-z0-9_-]{43}$/.test(u.searchParams.get("code") || "");
150
+ if (
151
+ u.pathname !== "/hermesdesk/callback" ||
152
+ u.searchParams.getAll("state").length !== 1 ||
153
+ u.searchParams.get("state") !== state ||
154
+ [...u.searchParams.keys()].some(
155
+ (k) => !["state", "code", "error"].includes(k),
156
+ ) ||
157
+ (!denied && !validCode)
158
+ )
159
+ return fail();
160
+ settled = true;
161
+ callbackResponse = res;
162
+ if (denied) rejectCallback(Error("Browser sign-in canceled."));
163
+ else resolveCallback(u.searchParams.get("code"));
164
+ });
165
+ server.headersTimeout = 10000;
166
+ server.requestTimeout = 10000;
167
+ await new Promise((resolve, reject) => {
168
+ server.once("error", reject);
169
+ server.listen(0, "127.0.0.1", resolve);
170
+ });
171
+ const redirectUri =
172
+ "http://127.0.0.1:" + server.address().port + "/hermesdesk/callback";
173
+ const authorization = new URL(metadata.authorization);
174
+ for (const [key, value] of Object.entries({
175
+ flow: "browser",
176
+ state,
177
+ challenge,
178
+ redirect_uri: redirectUri,
179
+ computer: os.hostname().slice(0, 80),
180
+ }))
181
+ authorization.searchParams.set(key, value);
182
+ const timer = setTimeout(
183
+ () =>
184
+ rejectCallback(
185
+ Error("Browser sign-in timed out. Run hermesdesk connect again."),
186
+ ),
187
+ timeoutMs,
188
+ );
189
+ try {
190
+ log("Sign in and approve this computer in your browser.");
191
+ log(
192
+ "If the browser does not open, open this link on this computer:\n" +
193
+ authorization.href,
194
+ );
195
+ Promise.resolve()
196
+ .then(() => launch(authorization.href))
197
+ .catch(() => {
198
+ log("Automatic browser opening was unavailable; use the link above.");
199
+ });
200
+ const code = await callback;
201
+ const response = await transport(metadata.token.href, {
202
+ method: "POST",
203
+ headers: {
204
+ "content-type": "application/json",
205
+ "User-Agent": "HermesDesk-CLI/1.0",
206
+ },
207
+ body: JSON.stringify({ code, verifier, redirectUri }),
208
+ signal: AbortSignal.timeout(20000),
209
+ });
210
+ if (response.status !== 200) {
211
+ await response.body?.cancel();
212
+ throw Error(
213
+ "Browser sign-in was not accepted or expired. Run connect again.",
214
+ );
215
+ }
216
+ const value = parseConnectionCode((await json(response)).connectionCode);
217
+ if (value.baseUrl !== endpoint(baseUrl))
218
+ throw Error("Sign-in returned credentials for a different endpoint.");
219
+ callbackResponse.writeHead(200, {
220
+ "content-type": "text/html; charset=utf-8",
221
+ "cache-control": "no-store",
222
+ "content-security-policy": "default-src 'none'; frame-ancestors 'none'",
223
+ "referrer-policy": "no-referrer",
224
+ connection: "close",
225
+ });
226
+ callbackResponse.end(
227
+ "<!doctype html><title>HermesDesk connected</title><h1>Computer approved</h1><p>Return to your terminal to finish connecting. You can close this tab.</p>",
228
+ );
229
+ return value;
230
+ } finally {
231
+ clearTimeout(timer);
232
+ if (callbackResponse && !callbackResponse.writableEnded) {
233
+ callbackResponse.writeHead(400, {
234
+ "content-type": "text/plain",
235
+ connection: "close",
236
+ });
237
+ callbackResponse.end("Sign-in could not finish. Check your terminal.");
238
+ }
239
+ if (callbackResponse && !callbackResponse.writableFinished) {
240
+ await new Promise((resolve) => {
241
+ const timer = setTimeout(resolve, 1000);
242
+ callbackResponse.once("finish", () => {
243
+ clearTimeout(timer);
244
+ resolve();
245
+ });
246
+ });
247
+ }
248
+ server.closeAllConnections();
249
+ await new Promise((resolve) => server.close(resolve));
250
+ }
251
+ }
package/src/config.js CHANGED
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import crypto from "node:crypto";
5
- export const VERSION = "0.1.0-alpha.1";
5
+ export const VERSION = "0.1.0-alpha.3";
6
6
  export const DEFAULTS = {
7
7
  baseUrl: null,
8
8
  model: null,
@@ -111,3 +111,12 @@ export function projectSessionDir(home, cwd) {
111
111
  .slice(0, 24),
112
112
  );
113
113
  }
114
+
115
+ export function supportedNode(version = process.versions.node) {
116
+ const [major, minor] = version.split(".").map(Number);
117
+ return (
118
+ Number.isInteger(major) &&
119
+ Number.isInteger(minor) &&
120
+ (major > 22 || (major === 22 && minor >= 19))
121
+ );
122
+ }
@@ -0,0 +1,45 @@
1
+ import { endpoint } from "./config.js";
2
+ export function validateAccess(access) {
3
+ if (access == null) return undefined;
4
+ if (
5
+ !access ||
6
+ typeof access !== "object" ||
7
+ !/^[A-Za-z0-9_-]{8,128}\.access$/.test(access.clientId || "") ||
8
+ !/^[A-Za-z0-9_-]{32,256}$/.test(access.clientSecret || "")
9
+ )
10
+ throw Error(
11
+ "Invalid Cloudflare Access credentials. Create a new connection code in HermesDesk.",
12
+ );
13
+ return { clientId: access.clientId, clientSecret: access.clientSecret };
14
+ }
15
+ export function parseConnectionCode(code) {
16
+ if (typeof code !== "string" || !/^hdc1_[A-Za-z0-9_-]{1,8000}$/.test(code))
17
+ throw Error(
18
+ "Paste the private connection code from HermesDesk Settings > Connect coding tools.",
19
+ );
20
+ let value;
21
+ try {
22
+ value = JSON.parse(
23
+ Buffer.from(code.slice(5), "base64url").toString("utf8"),
24
+ );
25
+ } catch {
26
+ throw Error("The connection code is invalid.");
27
+ }
28
+ if (
29
+ !value ||
30
+ value.v !== 1 ||
31
+ !/^[A-Za-z0-9_-]{48,128}$/.test(value.token || "") ||
32
+ !Number.isFinite(value.expires) ||
33
+ value.expires <= Date.now()
34
+ )
35
+ throw Error(
36
+ "The connection code is expired or invalid. Create a new connection in HermesDesk.",
37
+ );
38
+ const baseUrl = endpoint(value.baseUrl);
39
+ if (!baseUrl.startsWith("https://"))
40
+ throw Error("Connection codes require HTTPS.");
41
+ const access = validateAccess(value.access);
42
+ if (!access)
43
+ throw Error("Connection code is missing Cloudflare Access credentials.");
44
+ return { baseUrl, token: value.token, access };
45
+ }
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import { validateAccess } from "./connection.js";
2
3
  import path from "node:path";
3
4
  import { spawn } from "node:child_process";
4
5
  const PS = `$ErrorActionPreference='Stop'; Add-Type -AssemblyName System.Security; $r=([Console]::In.ReadToEnd() | ConvertFrom-Json); if ($r.action -eq 'protect') {$b=[Text.Encoding]::UTF8.GetBytes($r.value); [Console]::Out.Write([Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser)))} else {$b=[Convert]::FromBase64String($r.value); [Console]::Out.Write([Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser)))}`;
@@ -45,17 +46,32 @@ function dpapi(action, value) {
45
46
  p.stdin.end(JSON.stringify({ action, value }));
46
47
  });
47
48
  }
48
- export async function saveCredential(home, baseUrl, token) {
49
+ export async function saveCredential(home, baseUrl, token, access) {
49
50
  if (!/^[A-Za-z0-9_-]{48,128}$/.test(token))
50
51
  throw Error("Enter the HermesDesk inference API key.");
51
- const encrypted = await dpapi("protect", JSON.stringify({ baseUrl, token }));
52
+ const encrypted = await dpapi(
53
+ "protect",
54
+ JSON.stringify({ baseUrl, token, access: validateAccess(access) }),
55
+ );
52
56
  fs.mkdirSync(home, { recursive: true, mode: 0o700 });
53
57
  const file = path.join(home, "credential.dpapi");
54
58
  fs.writeFileSync(file + ".tmp", encrypted, { mode: 0o600 });
55
59
  fs.renameSync(file + ".tmp", file);
56
60
  }
57
61
  export async function getCredential(home, baseUrl) {
58
- if (process.env.HERMESDESK_API_KEY) return process.env.HERMESDESK_API_KEY;
62
+ return (await getConnection(home, baseUrl)).token;
63
+ }
64
+ export async function getConnection(home, baseUrl) {
65
+ const access =
66
+ process.env.HERMESDESK_ACCESS_CLIENT_ID ||
67
+ process.env.HERMESDESK_ACCESS_CLIENT_SECRET
68
+ ? validateAccess({
69
+ clientId: process.env.HERMESDESK_ACCESS_CLIENT_ID,
70
+ clientSecret: process.env.HERMESDESK_ACCESS_CLIENT_SECRET,
71
+ })
72
+ : undefined;
73
+ if (process.env.HERMESDESK_API_KEY)
74
+ return { token: process.env.HERMESDESK_API_KEY, access };
59
75
  let encrypted;
60
76
  try {
61
77
  encrypted = fs.readFileSync(path.join(home, "credential.dpapi"), "utf8");
@@ -69,7 +85,7 @@ export async function getCredential(home, baseUrl) {
69
85
  throw Error(
70
86
  "This key belongs to a different endpoint. Run hermesdesk connect.",
71
87
  );
72
- return value.token;
88
+ return { token: value.token, access: access || validateAccess(value.access) };
73
89
  }
74
90
  export function logout(home) {
75
91
  fs.rmSync(path.join(home, "credential.dpapi"), { force: true });
@@ -105,9 +121,9 @@ export async function hiddenInput(label) {
105
121
  }
106
122
  if (char === "\u007f" || char === "\b") text = text.slice(0, -1);
107
123
  else if (char >= " ") text += char;
108
- if (text.length > 1024) {
124
+ if (text.length > 8192) {
109
125
  done();
110
- reject(Error("API key is too long."));
126
+ reject(Error("Credential input is too long."));
111
127
  return;
112
128
  }
113
129
  }
package/src/transport.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import http from "node:http";
2
+ import { validateAccess } from "./connection.js";
2
3
  import https from "node:https";
3
4
  import { Readable } from "node:stream";
4
5
  import zlib from "node:zlib";
5
6
  import path from "node:path";
6
7
  import { spawn } from "node:child_process";
7
- import { PassThrough } from "node:stream";
8
8
  // Use Node's native HTTP transport. The public gateway challenged undici/fetch during testing.
9
9
  export async function nativeFetch(input, init) {
10
10
  const r = new Request(input, init),
@@ -59,8 +59,9 @@ export async function nativeFetch(input, init) {
59
59
  req.end(body);
60
60
  });
61
61
  }
62
- export function modelFetch(baseUrl) {
62
+ export function modelFetch(baseUrl, access) {
63
63
  const allowed = new URL(baseUrl);
64
+ access = validateAccess(access);
64
65
  return (input, init) => {
65
66
  const u = new URL(input instanceof Request ? input.url : String(input));
66
67
  if (
@@ -70,29 +71,49 @@ export function modelFetch(baseUrl) {
70
71
  u.hash
71
72
  )
72
73
  throw Error("Unexpected model endpoint.");
73
- return (process.platform === "win32" ? curlFetch : nativeFetch)(
74
- input,
75
- init,
76
- );
74
+ const request = new Request(input, init);
75
+ if (access) {
76
+ request.headers.set("CF-Access-Client-Id", access.clientId);
77
+ request.headers.set("CF-Access-Client-Secret", access.clientSecret);
78
+ }
79
+ return (process.platform === "win32" ? curlFetch : nativeFetch)(request);
77
80
  };
78
81
  }
79
- export async function discover(config, token) {
80
- const r = await modelFetch(config.baseUrl)(config.baseUrl + "/models", {
81
- headers: {
82
- Authorization: "Bearer " + token,
83
- "User-Agent": "HermesDesk-CLI/1.0",
82
+ export async function discover(config, token, access) {
83
+ const r = await modelFetch(config.baseUrl, access)(
84
+ config.baseUrl + "/models",
85
+ {
86
+ headers: {
87
+ Authorization: "Bearer " + token,
88
+ "User-Agent": "HermesDesk-CLI/1.0",
89
+ },
90
+ signal: AbortSignal.timeout(20000),
84
91
  },
85
- signal: AbortSignal.timeout(20000),
86
- });
92
+ );
87
93
  if (!r.ok) {
88
94
  await r.body?.cancel();
89
- throw Error(
90
- r.status === 401
91
- ? "API key is invalid, revoked or expired."
92
- : r.status === 403
93
- ? "Cloudflare rejected this client connection."
94
- : "Model discovery failed (HTTP " + r.status + ").",
95
+ const challenge =
96
+ r.status === 403 &&
97
+ (r.headers.get("cf-mitigated") === "challenge" ||
98
+ (r.headers.get("content-type") || "").includes("text/html"));
99
+ const error = new Error(
100
+ r.status === 401 &&
101
+ (r.headers.get("content-type") || "").includes("text/html")
102
+ ? "Cloudflare sign-in is required. Run hermesdesk connect to sign in in your browser."
103
+ : r.status === 401
104
+ ? "API key is invalid, revoked or expired."
105
+ : challenge
106
+ ? "Cloudflare blocked this API request with a browser challenge. The server owner needs to adjust protection for the API endpoint."
107
+ : r.status === 403 || r.status === 302
108
+ ? "Cloudflare Access denied this connection. Use a new HermesDesk connection code or check the Access credentials."
109
+ : "Model discovery failed (HTTP " + r.status + ").",
95
110
  );
111
+ error.code = challenge ? "CLOUDFLARE_CHALLENGE" : "MODEL_DISCOVERY_FAILED";
112
+ error.status = r.status;
113
+ const ray = r.headers.get("cf-ray");
114
+ if (ray && /^[A-Za-z0-9-]{1,100}$/.test(ray))
115
+ error.message += " Cloudflare Ray: " + ray;
116
+ throw error;
96
117
  }
97
118
  const data = await r.json();
98
119
  if (!Array.isArray(data.data))
@@ -125,7 +146,15 @@ export async function curlFetch(input, init) {
125
146
  'header = "Expect:"',
126
147
  ];
127
148
  for (const [key, value] of r.headers)
128
- if (["authorization", "content-type", "accept"].includes(key))
149
+ if (
150
+ [
151
+ "authorization",
152
+ "content-type",
153
+ "accept",
154
+ "cf-access-client-id",
155
+ "cf-access-client-secret",
156
+ ].includes(key)
157
+ )
129
158
  lines.push("header = " + curlQuote(key + ": " + value));
130
159
  if (data) lines.push("data-binary = " + curlQuote(data.toString("utf8")));
131
160
  return new Promise((resolve, reject) => {
@@ -134,6 +163,7 @@ export async function curlFetch(input, init) {
134
163
  [
135
164
  "--silent",
136
165
  "--show-error",
166
+ "--no-buffer",
137
167
  "--http1.1",
138
168
  "--include",
139
169
  "--compressed",
@@ -144,40 +174,58 @@ export async function curlFetch(input, init) {
144
174
  ],
145
175
  { windowsHide: true, stdio: ["pipe", "pipe", "pipe"] },
146
176
  );
147
- const stream = new PassThrough();
148
- let buffer = Buffer.alloc(0),
149
- headersDone = false,
150
- stderr = "",
151
- settled = false;
152
- const abort = () => {
177
+ let buffer = Buffer.alloc(0);
178
+ let headersDone = false,
179
+ settled = false,
180
+ bodyClosed = false,
181
+ controller;
182
+ const stopChild = () => {
183
+ child.stdout.pause();
153
184
  child.kill();
154
- stream.destroy(new DOMException("Request cancelled", "AbortError"));
185
+ };
186
+ const finishBody = (error) => {
187
+ if (bodyClosed) return;
188
+ bodyClosed = true;
189
+ if (controller) {
190
+ if (error) controller.error(error);
191
+ else controller.close();
192
+ }
193
+ };
194
+ const writeBody = (chunk) => {
195
+ if (bodyClosed || !controller || !chunk.length) return;
196
+ controller.enqueue(chunk);
197
+ if (controller.desiredSize <= 0) child.stdout.pause();
198
+ };
199
+ const abort = () => {
200
+ const error = new DOMException("Request cancelled", "AbortError");
201
+ finishBody(error);
202
+ stopChild();
155
203
  if (!settled) {
156
204
  settled = true;
157
- reject(new DOMException("Request cancelled", "AbortError"));
205
+ reject(error);
158
206
  }
159
207
  };
160
- stream.on("error", () => {});
161
- r.signal.addEventListener("abort", abort, { once: true });
162
- child.stderr.on("data", (b) => {
163
- if (stderr.length < 4096) stderr += b.toString();
164
- });
165
208
  const fail = () => {
209
+ if (bodyClosed) return;
166
210
  const error = new Error(
167
211
  "Windows HTTP transport failed" +
168
212
  (child.exitCode ? " (curl " + child.exitCode + ")" : "") +
169
213
  ". Check the server address and connection.",
170
214
  );
215
+ finishBody(error);
171
216
  if (!settled) {
172
217
  settled = true;
173
218
  reject(error);
174
- } else stream.destroy(error);
219
+ }
175
220
  };
221
+ r.signal.addEventListener("abort", abort, { once: true });
222
+ child.stderr.resume();
176
223
  child.on("error", fail);
177
224
  child.stdin.on("error", () => {});
178
225
  child.stdout.on("data", (chunk) => {
226
+ if (bodyClosed) return;
179
227
  if (headersDone) {
180
- if (!stream.write(chunk)) child.stdout.pause();
228
+ writeBody(chunk);
181
229
  return;
182
230
  }
183
231
  buffer = Buffer.concat([buffer, chunk]);
@@ -188,8 +236,8 @@ export async function curlFetch(input, init) {
188
236
  match = /^HTTP\/\S+ (\d{3})/.exec(rows.shift());
189
237
  buffer = buffer.subarray(end + 4);
190
238
  if (!match) {
191
- child.kill();
192
239
  fail();
240
+ stopChild();
193
241
  return;
194
242
  }
195
243
  const status = Number(match[1]);
@@ -204,29 +252,39 @@ export async function curlFetch(input, init) {
204
252
  headers.delete("content-length");
205
253
  headers.delete("transfer-encoding");
206
254
  headersDone = true;
207
- const response = new Response(
208
- [204, 205, 304].includes(status) ? null : Readable.toWeb(stream),
209
- { status, headers },
210
- );
255
+ const noBody = [204, 205, 304].includes(status) || r.method === "HEAD";
256
+ const body = noBody
257
+ ? null
258
+ : new ReadableStream({
259
+ start(value) {
260
+ controller = value;
261
+ },
262
+ pull() {
263
+ if (!bodyClosed) child.stdout.resume();
264
+ },
265
+ cancel() {
266
+ bodyClosed = true;
267
+ r.signal.removeEventListener("abort", abort);
268
+ stopChild();
269
+ },
270
+ });
271
+ const response = new Response(body, { status, headers });
211
272
  Object.defineProperty(response, "url", { value: r.url });
212
273
  settled = true;
213
274
  resolve(response);
214
- if (buffer.length && !stream.write(buffer)) child.stdout.pause();
275
+ writeBody(buffer);
215
276
  buffer = Buffer.alloc(0);
216
277
  break;
217
278
  }
218
279
  if (!headersDone && buffer.length > 65536) {
219
- child.kill();
220
280
  fail();
281
+ stopChild();
221
282
  }
222
283
  });
223
- stream.on("drain", () => child.stdout.resume());
224
- stream.on("close", () => {
225
- if (!child.stdout.readableEnded) child.kill();
226
- });
227
284
  child.on("close", (code) => {
228
285
  r.signal.removeEventListener("abort", abort);
229
- if (code === 0 && headersDone) stream.end();
286
+ if (bodyClosed) return;
287
+ if (code === 0 && headersDone) finishBody();
230
288
  else fail();
231
289
  });
232
290
  if (r.signal.aborted) {