hermesdesk-agent 0.1.0-alpha.2 → 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.2.** 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
 
@@ -18,11 +18,11 @@ hermesdesk.cmd connect
18
18
  hermesdesk.cmd doctor
19
19
  ```
20
20
 
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.2.tgz`.
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
22
 
23
- 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.
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
24
 
25
- For an Access-protected Worker, 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`.
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
26
 
27
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.
28
28
 
package/bin/hermesdesk.js CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  hiddenInput,
19
19
  logout,
20
20
  } from "../src/credentials.js";
21
+ import { browserLogin } from "../src/browser-login.js";
21
22
  import { parseConnectionCode, validateAccess } from "../src/connection.js";
22
23
  const privateValues = new Set();
23
24
  const protect = (value) => {
@@ -36,7 +37,7 @@ const clearAuthEnv = () => {
36
37
  import { discover } from "../src/transport.js";
37
38
  const help = `HermesDesk Agent ${VERSION} (Pi-based, Windows first)
38
39
 
39
- hermesdesk connect [--code | --url https://your-server.example/v1] [--cloudflare-access]
40
+ hermesdesk connect [--code | --url https://your-server.example/v1] [--manual | --cloudflare-access]
40
41
  hermesdesk doctor
41
42
  hermesdesk chat [--cwd PATH] [--continue | --session ID] [--read-only]
42
43
  hermesdesk run "REQUEST" [--cwd PATH] [--json] [--read-only]
@@ -55,6 +56,8 @@ async function main() {
55
56
  options: {
56
57
  url: { type: "string" },
57
58
  code: { type: "boolean" },
59
+ manual: { type: "boolean" },
60
+ "no-browser": { type: "boolean" },
58
61
  "cloudflare-access": { type: "boolean" },
59
62
  cwd: { type: "string" },
60
63
  session: { type: "string" },
@@ -121,6 +124,17 @@ async function main() {
121
124
  throw Error(
122
125
  "Enter your server URL, or use hermesdesk connect --url https://your-server.example/v1.",
123
126
  );
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
+ }
124
138
  const token = protect(
125
139
  imported?.token ||
126
140
  process.env.HERMESDESK_API_KEY ||
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "hermesdesk-agent",
3
- "version": "0.1.0-alpha.2",
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.2",
9
+ "version": "0.1.0-alpha.3",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/pi-coding-agent": "1.5.0"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hermesdesk-agent",
3
- "version": "0.1.0-alpha.2",
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": {
@@ -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.2";
5
+ export const VERSION = "0.1.0-alpha.3";
6
6
  export const DEFAULTS = {
7
7
  baseUrl: null,
8
8
  model: null,
package/src/transport.js CHANGED
@@ -97,13 +97,16 @@ export async function discover(config, token, access) {
97
97
  (r.headers.get("cf-mitigated") === "challenge" ||
98
98
  (r.headers.get("content-type") || "").includes("text/html"));
99
99
  const error = new Error(
100
- r.status === 401
101
- ? "API key is invalid, revoked or expired."
102
- : challenge
103
- ? "Cloudflare blocked this API request with a browser challenge. The server owner needs to adjust protection for the API endpoint."
104
- : r.status === 403 || r.status === 302
105
- ? "Cloudflare Access denied this connection. Use a new HermesDesk connection code or check the Access credentials."
106
- : "Model discovery failed (HTTP " + r.status + ").",
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 + ").",
107
110
  );
108
111
  error.code = challenge ? "CLOUDFLARE_CHALLENGE" : "MODEL_DISCOVERY_FAILED";
109
112
  error.status = r.status;