hermesdesk-agent 0.1.0-alpha.1 → 0.1.0-alpha.2
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 +14 -4
- package/bin/hermesdesk.js +81 -12
- package/npm-shrinkwrap.json +4 -3
- package/package.json +3 -2
- package/src/agent.js +2 -1
- package/src/config.js +10 -1
- package/src/connection.js +45 -0
- package/src/credentials.js +22 -6
- package/src/transport.js +100 -45
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/NKocur/hermesdesk-agent/actions/workflows/ci.yml)
|
|
4
4
|
|
|
5
|
-
**Windows alpha: 0.1.0-alpha.
|
|
5
|
+
**Windows alpha: 0.1.0-alpha.2.** 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,16 +10,22 @@ 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)
|
|
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
|
|
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
|
+
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`.
|
|
22
|
+
|
|
21
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.
|
|
22
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`.
|
|
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.
|
|
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
|
|
|
25
31
|
## Work on a project
|
|
@@ -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,30 @@ import {
|
|
|
12
13
|
projectSessionDir,
|
|
13
14
|
} from "../src/config.js";
|
|
14
15
|
import {
|
|
15
|
-
|
|
16
|
+
getConnection,
|
|
16
17
|
saveCredential,
|
|
17
18
|
hiddenInput,
|
|
18
19
|
logout,
|
|
19
20
|
} from "../src/credentials.js";
|
|
21
|
+
import { parseConnectionCode, validateAccess } from "../src/connection.js";
|
|
22
|
+
const privateValues = new Set();
|
|
23
|
+
const protect = (value) => {
|
|
24
|
+
if (value) privateValues.add(value);
|
|
25
|
+
return value;
|
|
26
|
+
};
|
|
27
|
+
const clearAuthEnv = () => {
|
|
28
|
+
for (const key of [
|
|
29
|
+
"HERMESDESK_API_KEY",
|
|
30
|
+
"HERMESDESK_ACCESS_CLIENT_ID",
|
|
31
|
+
"HERMESDESK_ACCESS_CLIENT_SECRET",
|
|
32
|
+
"HERMESDESK_CONNECTION_CODE",
|
|
33
|
+
])
|
|
34
|
+
delete process.env[key];
|
|
35
|
+
};
|
|
20
36
|
import { discover } from "../src/transport.js";
|
|
21
37
|
const help = `HermesDesk Agent ${VERSION} (Pi-based, Windows first)
|
|
22
38
|
|
|
23
|
-
hermesdesk connect [--url https://your-server.example/v1]
|
|
39
|
+
hermesdesk connect [--code | --url https://your-server.example/v1] [--cloudflare-access]
|
|
24
40
|
hermesdesk doctor
|
|
25
41
|
hermesdesk chat [--cwd PATH] [--continue | --session ID] [--read-only]
|
|
26
42
|
hermesdesk run "REQUEST" [--cwd PATH] [--json] [--read-only]
|
|
@@ -38,6 +54,8 @@ async function main() {
|
|
|
38
54
|
allowPositionals: true,
|
|
39
55
|
options: {
|
|
40
56
|
url: { type: "string" },
|
|
57
|
+
code: { type: "boolean" },
|
|
58
|
+
"cloudflare-access": { type: "boolean" },
|
|
41
59
|
cwd: { type: "string" },
|
|
42
60
|
session: { type: "string" },
|
|
43
61
|
continue: { type: "boolean" },
|
|
@@ -56,17 +74,40 @@ async function main() {
|
|
|
56
74
|
console.log(VERSION);
|
|
57
75
|
return;
|
|
58
76
|
}
|
|
77
|
+
if (!supportedNode())
|
|
78
|
+
throw Error(
|
|
79
|
+
"Node.js " +
|
|
80
|
+
process.versions.node +
|
|
81
|
+
" 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.",
|
|
82
|
+
);
|
|
59
83
|
const command = p.shift() || "chat",
|
|
60
84
|
home = configHome();
|
|
61
85
|
process.env.PI_CODING_AGENT_DIR = path.join(home, "pi");
|
|
62
86
|
let config = loadConfig(home);
|
|
63
87
|
if (command === "connect") {
|
|
88
|
+
let imported;
|
|
89
|
+
if (v.code || process.env.HERMESDESK_CONNECTION_CODE) {
|
|
90
|
+
if (v.url || v["cloudflare-access"])
|
|
91
|
+
throw Error(
|
|
92
|
+
"Use --code on its own; the private code includes the endpoint and credentials.",
|
|
93
|
+
);
|
|
94
|
+
imported = parseConnectionCode(
|
|
95
|
+
protect(
|
|
96
|
+
process.env.HERMESDESK_CONNECTION_CODE ||
|
|
97
|
+
(await hiddenInput(
|
|
98
|
+
"Private HermesDesk connection code (hidden): ",
|
|
99
|
+
)),
|
|
100
|
+
),
|
|
101
|
+
);
|
|
102
|
+
config = validateConfig({ ...config, baseUrl: imported.baseUrl });
|
|
103
|
+
console.log("Connecting to " + config.baseUrl);
|
|
104
|
+
}
|
|
64
105
|
if (v.url) config = validateConfig({ ...config, baseUrl: v.url });
|
|
65
106
|
const rl = readline.createInterface({
|
|
66
107
|
input: process.stdin,
|
|
67
108
|
output: process.stdout,
|
|
68
109
|
});
|
|
69
|
-
if (!v.url && process.stdin.isTTY) {
|
|
110
|
+
if (!imported && !v.url && process.stdin.isTTY) {
|
|
70
111
|
const answer = await rl.question(
|
|
71
112
|
config.baseUrl
|
|
72
113
|
? "Server [" + config.baseUrl + "]: "
|
|
@@ -80,13 +121,33 @@ async function main() {
|
|
|
80
121
|
throw Error(
|
|
81
122
|
"Enter your server URL, or use hermesdesk connect --url https://your-server.example/v1.",
|
|
82
123
|
);
|
|
83
|
-
const token =
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
124
|
+
const token = protect(
|
|
125
|
+
imported?.token ||
|
|
126
|
+
process.env.HERMESDESK_API_KEY ||
|
|
127
|
+
(await hiddenInput("HermesDesk API key (hidden): ")),
|
|
128
|
+
);
|
|
129
|
+
let access = imported?.access;
|
|
130
|
+
if (
|
|
131
|
+
!access &&
|
|
132
|
+
(v["cloudflare-access"] ||
|
|
133
|
+
process.env.HERMESDESK_ACCESS_CLIENT_ID ||
|
|
134
|
+
process.env.HERMESDESK_ACCESS_CLIENT_SECRET)
|
|
135
|
+
) {
|
|
136
|
+
access = validateAccess({
|
|
137
|
+
clientId:
|
|
138
|
+
process.env.HERMESDESK_ACCESS_CLIENT_ID ||
|
|
139
|
+
(await hiddenInput("Cloudflare Access client ID (hidden): ")),
|
|
140
|
+
clientSecret:
|
|
141
|
+
process.env.HERMESDESK_ACCESS_CLIENT_SECRET ||
|
|
142
|
+
(await hiddenInput("Cloudflare Access client secret (hidden): ")),
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
protect(access?.clientSecret);
|
|
146
|
+
clearAuthEnv();
|
|
147
|
+
const models = await discover(config, token, access);
|
|
87
148
|
if (!models.length) throw Error("No models are available.");
|
|
88
149
|
if (!models.includes(config.model)) config.model = models[0];
|
|
89
|
-
await saveCredential(home, config.baseUrl, token);
|
|
150
|
+
await saveCredential(home, config.baseUrl, token, access);
|
|
90
151
|
saveConfig(config, home);
|
|
91
152
|
console.log(
|
|
92
153
|
"Connected. Credential protected for your Windows account.\nModel: " +
|
|
@@ -151,10 +212,12 @@ async function main() {
|
|
|
151
212
|
throw Error("Unknown command. Use hermesdesk --help.");
|
|
152
213
|
if (!config.baseUrl || !config.model)
|
|
153
214
|
throw Error("Not connected. Run hermesdesk connect first.");
|
|
154
|
-
const token = await
|
|
155
|
-
|
|
215
|
+
const { token, access } = await getConnection(home, config.baseUrl);
|
|
216
|
+
protect(token);
|
|
217
|
+
protect(access?.clientSecret);
|
|
218
|
+
clearAuthEnv();
|
|
156
219
|
if (command === "doctor") {
|
|
157
|
-
const models = await discover(config, token);
|
|
220
|
+
const models = await discover(config, token, access);
|
|
158
221
|
console.log(
|
|
159
222
|
JSON.stringify(
|
|
160
223
|
{
|
|
@@ -186,6 +249,7 @@ async function main() {
|
|
|
186
249
|
config,
|
|
187
250
|
home,
|
|
188
251
|
token,
|
|
252
|
+
access,
|
|
189
253
|
cwd,
|
|
190
254
|
readOnly: !!v["read-only"],
|
|
191
255
|
approveWrites: !!v["approve-writes"],
|
|
@@ -216,7 +280,12 @@ async function main() {
|
|
|
216
280
|
}
|
|
217
281
|
main().catch((e) => {
|
|
218
282
|
let message = e.message || "Operation failed.";
|
|
219
|
-
for (const secret of [
|
|
283
|
+
for (const secret of [
|
|
284
|
+
...privateValues,
|
|
285
|
+
process.env.HERMESDESK_API_KEY,
|
|
286
|
+
process.env.HERMESDESK_ACCESS_CLIENT_SECRET,
|
|
287
|
+
process.env.HERMESDESK_CONNECTION_CODE,
|
|
288
|
+
])
|
|
220
289
|
if (secret) message = message.split(secret).join("[redacted]");
|
|
221
290
|
if (/<!doctype|<html/i.test(message))
|
|
222
291
|
message =
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hermesdesk-agent",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.2",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "hermesdesk-agent",
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.2",
|
|
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.
|
|
3
|
+
"version": "0.1.0-alpha.2",
|
|
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",
|
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.
|
|
5
|
+
export const VERSION = "0.1.0-alpha.2";
|
|
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
|
+
}
|
package/src/credentials.js
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
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 >
|
|
124
|
+
if (text.length > 8192) {
|
|
109
125
|
done();
|
|
110
|
-
reject(Error("
|
|
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,46 @@ export function modelFetch(baseUrl) {
|
|
|
70
71
|
u.hash
|
|
71
72
|
)
|
|
72
73
|
throw Error("Unexpected model endpoint.");
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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)(
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
-
|
|
86
|
-
});
|
|
92
|
+
);
|
|
87
93
|
if (!r.ok) {
|
|
88
94
|
await r.body?.cancel();
|
|
89
|
-
|
|
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(
|
|
90
100
|
r.status === 401
|
|
91
101
|
? "API key is invalid, revoked or expired."
|
|
92
|
-
:
|
|
93
|
-
? "Cloudflare
|
|
94
|
-
:
|
|
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 + ").",
|
|
95
107
|
);
|
|
108
|
+
error.code = challenge ? "CLOUDFLARE_CHALLENGE" : "MODEL_DISCOVERY_FAILED";
|
|
109
|
+
error.status = r.status;
|
|
110
|
+
const ray = r.headers.get("cf-ray");
|
|
111
|
+
if (ray && /^[A-Za-z0-9-]{1,100}$/.test(ray))
|
|
112
|
+
error.message += " Cloudflare Ray: " + ray;
|
|
113
|
+
throw error;
|
|
96
114
|
}
|
|
97
115
|
const data = await r.json();
|
|
98
116
|
if (!Array.isArray(data.data))
|
|
@@ -125,7 +143,15 @@ export async function curlFetch(input, init) {
|
|
|
125
143
|
'header = "Expect:"',
|
|
126
144
|
];
|
|
127
145
|
for (const [key, value] of r.headers)
|
|
128
|
-
if (
|
|
146
|
+
if (
|
|
147
|
+
[
|
|
148
|
+
"authorization",
|
|
149
|
+
"content-type",
|
|
150
|
+
"accept",
|
|
151
|
+
"cf-access-client-id",
|
|
152
|
+
"cf-access-client-secret",
|
|
153
|
+
].includes(key)
|
|
154
|
+
)
|
|
129
155
|
lines.push("header = " + curlQuote(key + ": " + value));
|
|
130
156
|
if (data) lines.push("data-binary = " + curlQuote(data.toString("utf8")));
|
|
131
157
|
return new Promise((resolve, reject) => {
|
|
@@ -134,6 +160,7 @@ export async function curlFetch(input, init) {
|
|
|
134
160
|
[
|
|
135
161
|
"--silent",
|
|
136
162
|
"--show-error",
|
|
163
|
+
"--no-buffer",
|
|
137
164
|
"--http1.1",
|
|
138
165
|
"--include",
|
|
139
166
|
"--compressed",
|
|
@@ -144,40 +171,58 @@ export async function curlFetch(input, init) {
|
|
|
144
171
|
],
|
|
145
172
|
{ windowsHide: true, stdio: ["pipe", "pipe", "pipe"] },
|
|
146
173
|
);
|
|
147
|
-
|
|
148
|
-
let
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const
|
|
174
|
+
let buffer = Buffer.alloc(0);
|
|
175
|
+
let headersDone = false,
|
|
176
|
+
settled = false,
|
|
177
|
+
bodyClosed = false,
|
|
178
|
+
controller;
|
|
179
|
+
const stopChild = () => {
|
|
180
|
+
child.stdout.pause();
|
|
153
181
|
child.kill();
|
|
154
|
-
|
|
182
|
+
};
|
|
183
|
+
const finishBody = (error) => {
|
|
184
|
+
if (bodyClosed) return;
|
|
185
|
+
bodyClosed = true;
|
|
186
|
+
if (controller) {
|
|
187
|
+
if (error) controller.error(error);
|
|
188
|
+
else controller.close();
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
const writeBody = (chunk) => {
|
|
192
|
+
if (bodyClosed || !controller || !chunk.length) return;
|
|
193
|
+
controller.enqueue(chunk);
|
|
194
|
+
if (controller.desiredSize <= 0) child.stdout.pause();
|
|
195
|
+
};
|
|
196
|
+
const abort = () => {
|
|
197
|
+
const error = new DOMException("Request cancelled", "AbortError");
|
|
198
|
+
finishBody(error);
|
|
199
|
+
stopChild();
|
|
155
200
|
if (!settled) {
|
|
156
201
|
settled = true;
|
|
157
|
-
reject(
|
|
202
|
+
reject(error);
|
|
158
203
|
}
|
|
159
204
|
};
|
|
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
205
|
const fail = () => {
|
|
206
|
+
if (bodyClosed) return;
|
|
166
207
|
const error = new Error(
|
|
167
208
|
"Windows HTTP transport failed" +
|
|
168
209
|
(child.exitCode ? " (curl " + child.exitCode + ")" : "") +
|
|
169
210
|
". Check the server address and connection.",
|
|
170
211
|
);
|
|
212
|
+
finishBody(error);
|
|
171
213
|
if (!settled) {
|
|
172
214
|
settled = true;
|
|
173
215
|
reject(error);
|
|
174
|
-
}
|
|
216
|
+
}
|
|
175
217
|
};
|
|
218
|
+
r.signal.addEventListener("abort", abort, { once: true });
|
|
219
|
+
child.stderr.resume();
|
|
176
220
|
child.on("error", fail);
|
|
177
221
|
child.stdin.on("error", () => {});
|
|
178
222
|
child.stdout.on("data", (chunk) => {
|
|
223
|
+
if (bodyClosed) return;
|
|
179
224
|
if (headersDone) {
|
|
180
|
-
|
|
225
|
+
writeBody(chunk);
|
|
181
226
|
return;
|
|
182
227
|
}
|
|
183
228
|
buffer = Buffer.concat([buffer, chunk]);
|
|
@@ -188,8 +233,8 @@ export async function curlFetch(input, init) {
|
|
|
188
233
|
match = /^HTTP\/\S+ (\d{3})/.exec(rows.shift());
|
|
189
234
|
buffer = buffer.subarray(end + 4);
|
|
190
235
|
if (!match) {
|
|
191
|
-
child.kill();
|
|
192
236
|
fail();
|
|
237
|
+
stopChild();
|
|
193
238
|
return;
|
|
194
239
|
}
|
|
195
240
|
const status = Number(match[1]);
|
|
@@ -204,29 +249,39 @@ export async function curlFetch(input, init) {
|
|
|
204
249
|
headers.delete("content-length");
|
|
205
250
|
headers.delete("transfer-encoding");
|
|
206
251
|
headersDone = true;
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
252
|
+
const noBody = [204, 205, 304].includes(status) || r.method === "HEAD";
|
|
253
|
+
const body = noBody
|
|
254
|
+
? null
|
|
255
|
+
: new ReadableStream({
|
|
256
|
+
start(value) {
|
|
257
|
+
controller = value;
|
|
258
|
+
},
|
|
259
|
+
pull() {
|
|
260
|
+
if (!bodyClosed) child.stdout.resume();
|
|
261
|
+
},
|
|
262
|
+
cancel() {
|
|
263
|
+
bodyClosed = true;
|
|
264
|
+
r.signal.removeEventListener("abort", abort);
|
|
265
|
+
stopChild();
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
const response = new Response(body, { status, headers });
|
|
211
269
|
Object.defineProperty(response, "url", { value: r.url });
|
|
212
270
|
settled = true;
|
|
213
271
|
resolve(response);
|
|
214
|
-
|
|
272
|
+
writeBody(buffer);
|
|
215
273
|
buffer = Buffer.alloc(0);
|
|
216
274
|
break;
|
|
217
275
|
}
|
|
218
276
|
if (!headersDone && buffer.length > 65536) {
|
|
219
|
-
child.kill();
|
|
220
277
|
fail();
|
|
278
|
+
stopChild();
|
|
221
279
|
}
|
|
222
280
|
});
|
|
223
|
-
stream.on("drain", () => child.stdout.resume());
|
|
224
|
-
stream.on("close", () => {
|
|
225
|
-
if (!child.stdout.readableEnded) child.kill();
|
|
226
|
-
});
|
|
227
281
|
child.on("close", (code) => {
|
|
228
282
|
r.signal.removeEventListener("abort", abort);
|
|
229
|
-
if (
|
|
283
|
+
if (bodyClosed) return;
|
|
284
|
+
if (code === 0 && headersDone) finishBody();
|
|
230
285
|
else fail();
|
|
231
286
|
});
|
|
232
287
|
if (r.signal.aborted) {
|