@anusornneal/chat-relay 0.11.2 → 0.12.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/README.md +21 -2
- package/agent/capability-scheduler.mjs +3 -1
- package/agent/connection-state.mjs +19 -0
- package/agent/lifecycle.mjs +68 -4
- package/agent/local-agent.mjs +34 -10
- package/cli/config.mjs +45 -9
- package/cli/index.mjs +37 -5
- package/cli/relay-health.mjs +185 -0
- package/cli/remote.mjs +37 -5
- package/cli/secret-store.mjs +223 -0
- package/cli/self-update.mjs +88 -0
- package/cli/tui.mjs +289 -52
- package/package.json +8 -2
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
export const RELAY_HEALTH_CHECK_INTERVAL_MS = 5 * 60 * 1000;
|
|
2
|
+
export const RELAY_HEALTH_CHECK_TIMEOUT_MS = 8 * 1000;
|
|
3
|
+
export const RELAY_HEALTH_LIMITED_INTERVAL_MS = 60 * 60 * 1000;
|
|
4
|
+
export const RELAY_HEALTH_CLOUDFLARE_ERROR_INTERVAL_MS = 15 * 60 * 1000;
|
|
5
|
+
|
|
6
|
+
export function relayHealthRetryDelay(
|
|
7
|
+
health,
|
|
8
|
+
intervalMs = RELAY_HEALTH_CHECK_INTERVAL_MS,
|
|
9
|
+
{
|
|
10
|
+
limitedIntervalMs = RELAY_HEALTH_LIMITED_INTERVAL_MS,
|
|
11
|
+
cloudflareErrorIntervalMs = RELAY_HEALTH_CLOUDFLARE_ERROR_INTERVAL_MS,
|
|
12
|
+
} = {},
|
|
13
|
+
) {
|
|
14
|
+
const base = Math.max(1000, Number(intervalMs) || RELAY_HEALTH_CHECK_INTERVAL_MS);
|
|
15
|
+
if (health?.state === "limited") return Math.max(base, Number(limitedIntervalMs) || RELAY_HEALTH_LIMITED_INTERVAL_MS);
|
|
16
|
+
if (health?.state === "cloudflare-error") {
|
|
17
|
+
return Math.max(base, Number(cloudflareErrorIntervalMs) || RELAY_HEALTH_CLOUDFLARE_ERROR_INTERVAL_MS);
|
|
18
|
+
}
|
|
19
|
+
return base;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const MAX_RESPONSE_BYTES = 4096;
|
|
23
|
+
|
|
24
|
+
async function readResponseText(response) {
|
|
25
|
+
const reader = response.body?.getReader?.();
|
|
26
|
+
if (!reader) return String(await response.text()).slice(0, MAX_RESPONSE_BYTES);
|
|
27
|
+
|
|
28
|
+
const chunks = [];
|
|
29
|
+
let length = 0;
|
|
30
|
+
while (length < MAX_RESPONSE_BYTES) {
|
|
31
|
+
const { done, value } = await reader.read();
|
|
32
|
+
if (done) break;
|
|
33
|
+
const remaining = MAX_RESPONSE_BYTES - length;
|
|
34
|
+
const chunk = value.subarray(0, remaining);
|
|
35
|
+
chunks.push(chunk);
|
|
36
|
+
length += chunk.byteLength;
|
|
37
|
+
if (chunk.byteLength < value.byteLength) {
|
|
38
|
+
await reader.cancel().catch(() => {});
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
await reader.cancel().catch(() => {});
|
|
43
|
+
|
|
44
|
+
const bytes = new Uint8Array(length);
|
|
45
|
+
let offset = 0;
|
|
46
|
+
for (const chunk of chunks) {
|
|
47
|
+
bytes.set(chunk, offset);
|
|
48
|
+
offset += chunk.byteLength;
|
|
49
|
+
}
|
|
50
|
+
return new TextDecoder().decode(bytes);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function classifyResponse(response, body) {
|
|
54
|
+
const cloudflareError = body.match(/\berror(?:\s+code)?\s*[:#]?\s*(1\d{3})\b/i);
|
|
55
|
+
if (cloudflareError) {
|
|
56
|
+
const code = Number(cloudflareError[1]);
|
|
57
|
+
return code === 1027
|
|
58
|
+
? { state: "limited", code }
|
|
59
|
+
: { state: "cloudflare-error", code };
|
|
60
|
+
}
|
|
61
|
+
if (response.status === 401) return { state: "unauthorized", code: response.status };
|
|
62
|
+
if (response.status === 403) return { state: "unauthorized", code: response.status };
|
|
63
|
+
if (response.status === 429) return { state: "limited", code: 429 };
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
const health = JSON.parse(body);
|
|
67
|
+
if (health?.error === "relay_unavailable") return { state: "unavailable", reason: "relay_unavailable" };
|
|
68
|
+
if (!response.ok) return { state: "unavailable", code: response.status };
|
|
69
|
+
if (health?.reauthorizationRequired === true) return { state: "reauthorize" };
|
|
70
|
+
if (health?.authorized === false) {
|
|
71
|
+
return health?.enabled === false
|
|
72
|
+
? { state: "agent-disabled" }
|
|
73
|
+
: { state: "agent-access" };
|
|
74
|
+
}
|
|
75
|
+
if (health?.online === true) return { state: "reachable" };
|
|
76
|
+
if (health?.online === false) return { state: "unavailable", reason: "agent_offline" };
|
|
77
|
+
} catch {}
|
|
78
|
+
if (!response.ok) return { state: "unavailable", code: response.status };
|
|
79
|
+
return { state: "unavailable", code: response.status };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function checkRelayHealth(relayUrl, {
|
|
83
|
+
fetchImpl = globalThis.fetch,
|
|
84
|
+
userToken,
|
|
85
|
+
agentId,
|
|
86
|
+
signal,
|
|
87
|
+
timeoutMs = RELAY_HEALTH_CHECK_TIMEOUT_MS,
|
|
88
|
+
} = {}) {
|
|
89
|
+
if (typeof fetchImpl !== "function") return { state: "unavailable" };
|
|
90
|
+
|
|
91
|
+
let healthUrl;
|
|
92
|
+
try {
|
|
93
|
+
healthUrl = new URL(relayUrl);
|
|
94
|
+
if (healthUrl.protocol !== "http:" && healthUrl.protocol !== "https:") {
|
|
95
|
+
return { state: "unavailable" };
|
|
96
|
+
}
|
|
97
|
+
healthUrl.pathname = `${healthUrl.pathname.replace(/\/+$/, "")}/status`;
|
|
98
|
+
healthUrl.search = "";
|
|
99
|
+
if (agentId) healthUrl.searchParams.set("agentId", String(agentId));
|
|
100
|
+
healthUrl.hash = "";
|
|
101
|
+
} catch {
|
|
102
|
+
return { state: "unavailable" };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const controller = new AbortController();
|
|
106
|
+
const timeout = setTimeout(() => controller.abort(), Math.max(1, Number(timeoutMs) || RELAY_HEALTH_CHECK_TIMEOUT_MS));
|
|
107
|
+
const abort = () => controller.abort();
|
|
108
|
+
if (signal?.aborted) controller.abort();
|
|
109
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
const response = await fetchImpl(healthUrl, {
|
|
113
|
+
method: "GET",
|
|
114
|
+
headers: {
|
|
115
|
+
accept: "application/json",
|
|
116
|
+
...(userToken ? { authorization: `Bearer ${userToken}` } : {}),
|
|
117
|
+
},
|
|
118
|
+
redirect: "manual",
|
|
119
|
+
cache: "no-store",
|
|
120
|
+
signal: controller.signal,
|
|
121
|
+
});
|
|
122
|
+
const body = await readResponseText(response);
|
|
123
|
+
return classifyResponse(response, body);
|
|
124
|
+
} catch {
|
|
125
|
+
return { state: "unavailable" };
|
|
126
|
+
} finally {
|
|
127
|
+
clearTimeout(timeout);
|
|
128
|
+
signal?.removeEventListener("abort", abort);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function startRelayHealthMonitor(relayUrl, {
|
|
133
|
+
onStatus,
|
|
134
|
+
// Per active TUI, this adds 288 Worker requests and up to 864 DO fetches daily.
|
|
135
|
+
intervalMs = RELAY_HEALTH_CHECK_INTERVAL_MS,
|
|
136
|
+
...checkOptions
|
|
137
|
+
} = {}) {
|
|
138
|
+
let stopped = false;
|
|
139
|
+
let timer = null;
|
|
140
|
+
let activeRequest = null;
|
|
141
|
+
let rerunRequested = false;
|
|
142
|
+
let cooldownUntil = 0;
|
|
143
|
+
const baseIntervalMs = Math.max(1000, Number(intervalMs) || RELAY_HEALTH_CHECK_INTERVAL_MS);
|
|
144
|
+
|
|
145
|
+
const check = async () => {
|
|
146
|
+
if (stopped || activeRequest) return;
|
|
147
|
+
const controller = new AbortController();
|
|
148
|
+
activeRequest = controller;
|
|
149
|
+
const result = await checkRelayHealth(relayUrl, { ...checkOptions, signal: controller.signal });
|
|
150
|
+
const shouldRerun = rerunRequested;
|
|
151
|
+
rerunRequested = false;
|
|
152
|
+
activeRequest = null;
|
|
153
|
+
if (stopped) return;
|
|
154
|
+
|
|
155
|
+
const retryDelay = relayHealthRetryDelay(result, baseIntervalMs, checkOptions);
|
|
156
|
+
const underCloudflarePressure = retryDelay > baseIntervalMs;
|
|
157
|
+
const rerunImmediately = shouldRerun && !underCloudflarePressure;
|
|
158
|
+
if (!shouldRerun || underCloudflarePressure) {
|
|
159
|
+
try { onStatus?.(result); } catch {}
|
|
160
|
+
}
|
|
161
|
+
cooldownUntil = underCloudflarePressure ? Date.now() + retryDelay : 0;
|
|
162
|
+
timer = setTimeout(check, rerunImmediately ? 0 : retryDelay);
|
|
163
|
+
timer.unref?.();
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
void check();
|
|
167
|
+
const stop = () => {
|
|
168
|
+
stopped = true;
|
|
169
|
+
if (timer) clearTimeout(timer);
|
|
170
|
+
activeRequest?.abort();
|
|
171
|
+
};
|
|
172
|
+
stop.checkNow = () => {
|
|
173
|
+
if (stopped) return false;
|
|
174
|
+
if (cooldownUntil > Date.now()) return false;
|
|
175
|
+
if (timer) clearTimeout(timer);
|
|
176
|
+
timer = null;
|
|
177
|
+
if (activeRequest) {
|
|
178
|
+
rerunRequested = true;
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
void check();
|
|
182
|
+
return true;
|
|
183
|
+
};
|
|
184
|
+
return stop;
|
|
185
|
+
}
|
package/cli/remote.mjs
CHANGED
|
@@ -5,13 +5,18 @@ import { loadConfig, saveConfig } from "./config.mjs";
|
|
|
5
5
|
import { login, requestJson } from "./device-login.mjs";
|
|
6
6
|
import { acquireRunnerOwnership, RunnerAlreadyActiveError } from "./runner-ownership.mjs";
|
|
7
7
|
import { getAgentVersion } from "../agent/protocol.mjs";
|
|
8
|
+
import { AGENT_UPGRADE_EXIT_CODE } from "../agent/lifecycle.mjs";
|
|
8
9
|
import { RemoteTui, shouldUseTui } from "./tui.mjs";
|
|
10
|
+
import { startRelayHealthMonitor } from "./relay-health.mjs";
|
|
9
11
|
|
|
10
12
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
11
13
|
let stopping = false;
|
|
12
14
|
|
|
13
15
|
export function shouldRestartAgent(result, stoppingNow = false) {
|
|
14
|
-
return !stoppingNow
|
|
16
|
+
return !stoppingNow
|
|
17
|
+
&& result?.code !== 2
|
|
18
|
+
&& result?.code !== 3
|
|
19
|
+
&& result?.code !== AGENT_UPGRADE_EXIT_CODE;
|
|
15
20
|
}
|
|
16
21
|
|
|
17
22
|
export function protocolCompatibility(agentProtocolVersion, expectedProtocolVersion) {
|
|
@@ -57,7 +62,7 @@ function printSummary(config) {
|
|
|
57
62
|
console.log("");
|
|
58
63
|
}
|
|
59
64
|
|
|
60
|
-
function spawnAgent(config, { tui = null } = {}) {
|
|
65
|
+
function spawnAgent(config, { tui = null, onConnectionState = null } = {}) {
|
|
61
66
|
const agentPath = path.join(packageRoot, "agent", "local-agent.mjs");
|
|
62
67
|
const cwd = String(config.allowedRoots || process.cwd()).split(";")[0] || process.cwd();
|
|
63
68
|
const useTui = Boolean(tui);
|
|
@@ -77,7 +82,12 @@ function spawnAgent(config, { tui = null } = {}) {
|
|
|
77
82
|
stdio: useTui ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
|
|
78
83
|
windowsHide: false,
|
|
79
84
|
});
|
|
80
|
-
if (useTui) child.on("message", (message) =>
|
|
85
|
+
if (useTui) child.on("message", (message) => {
|
|
86
|
+
tui.handleMessage(message);
|
|
87
|
+
if (message?.type === "chat-relay-ui" && message.event === "connection") {
|
|
88
|
+
onConnectionState?.(message.state);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
81
91
|
return child;
|
|
82
92
|
}
|
|
83
93
|
|
|
@@ -98,6 +108,8 @@ export async function remote(options = {}) {
|
|
|
98
108
|
return 1;
|
|
99
109
|
}
|
|
100
110
|
let tui = null;
|
|
111
|
+
let stopRelayHealthMonitor = null;
|
|
112
|
+
let supervisorCode = 0;
|
|
101
113
|
try {
|
|
102
114
|
if (options.allowedRoot && options.allowedRoot !== config.allowedRoots) {
|
|
103
115
|
config = { ...config, allowedRoots: options.allowedRoot };
|
|
@@ -110,11 +122,23 @@ export async function remote(options = {}) {
|
|
|
110
122
|
|
|
111
123
|
const useTui = shouldUseTui(options);
|
|
112
124
|
tui = useTui ? new RemoteTui({ config, version: getAgentVersion() }) : null;
|
|
113
|
-
if (tui)
|
|
125
|
+
if (tui) {
|
|
126
|
+
tui.start();
|
|
127
|
+
stopRelayHealthMonitor = startRelayHealthMonitor(config.relayUrl, {
|
|
128
|
+
userToken: config.userToken,
|
|
129
|
+
agentId: config.agentId,
|
|
130
|
+
onStatus: (health) => tui?.setRelayHealth(health),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
114
133
|
else printSummary(config);
|
|
115
134
|
|
|
116
135
|
while (!stopping) {
|
|
117
|
-
const child = spawnAgent(config, {
|
|
136
|
+
const child = spawnAgent(config, {
|
|
137
|
+
tui,
|
|
138
|
+
onConnectionState: (state) => {
|
|
139
|
+
if (state === "connected") stopRelayHealthMonitor?.checkNow?.();
|
|
140
|
+
},
|
|
141
|
+
});
|
|
118
142
|
|
|
119
143
|
const stop = () => {
|
|
120
144
|
stopping = true;
|
|
@@ -146,6 +170,12 @@ export async function remote(options = {}) {
|
|
|
146
170
|
console.log("Agent restart requested. Restarting local agent...");
|
|
147
171
|
continue;
|
|
148
172
|
}
|
|
173
|
+
if (result.code === AGENT_UPGRADE_EXIT_CODE) {
|
|
174
|
+
console.log("Agent upgrade requested. Handing off to the latest package...");
|
|
175
|
+
supervisorCode = AGENT_UPGRADE_EXIT_CODE;
|
|
176
|
+
stopping = true;
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
149
179
|
|
|
150
180
|
if (shouldRestartAgent(result, stopping)) {
|
|
151
181
|
console.error(
|
|
@@ -155,9 +185,11 @@ export async function remote(options = {}) {
|
|
|
155
185
|
}
|
|
156
186
|
}
|
|
157
187
|
} finally {
|
|
188
|
+
try { stopRelayHealthMonitor?.(); } catch {}
|
|
158
189
|
try { tui?.stop?.(); } catch {}
|
|
159
190
|
await ownership.release();
|
|
160
191
|
}
|
|
192
|
+
return supervisorCode;
|
|
161
193
|
}
|
|
162
194
|
|
|
163
195
|
export { validateConfig };
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
const KEYCHAIN_SERVICE = "com.anusornneal.chat-relay";
|
|
6
|
+
const SECRET_KEYS = ["userToken", "agentToken"];
|
|
7
|
+
|
|
8
|
+
function normalizedSecrets(value = {}) {
|
|
9
|
+
const result = {};
|
|
10
|
+
for (const key of SECRET_KEYS) {
|
|
11
|
+
const secret = value?.[key];
|
|
12
|
+
if (typeof secret === "string" && secret.length > 0) result[key] = secret;
|
|
13
|
+
}
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function fallbackPath(dir) {
|
|
18
|
+
return path.join(dir, "secrets.json");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function dpapiPath(dir) {
|
|
22
|
+
return path.join(dir, "secrets.dpapi");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function writePrivateFile(file, content) {
|
|
26
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
27
|
+
fs.writeFileSync(file, content, { encoding: "utf8", mode: 0o600 });
|
|
28
|
+
try { fs.chmodSync(file, 0o600); } catch {}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function removeFile(file) {
|
|
32
|
+
try { fs.rmSync(file, { force: true }); } catch {}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function resolveStore({ store, platform = process.platform, env = process.env } = {}) {
|
|
36
|
+
const requested = String(store || env?.CHAT_RELAY_SECRET_STORE || "").trim().toLowerCase();
|
|
37
|
+
if (requested === "keychain" || requested === "dpapi" || requested === "file") return requested;
|
|
38
|
+
if (platform === "darwin") return "keychain";
|
|
39
|
+
if (platform === "win32") return "dpapi";
|
|
40
|
+
return "file";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function readFallback(dir) {
|
|
44
|
+
const file = fallbackPath(dir);
|
|
45
|
+
if (!fs.existsSync(file)) return {};
|
|
46
|
+
try {
|
|
47
|
+
return normalizedSecrets(JSON.parse(fs.readFileSync(file, "utf8")));
|
|
48
|
+
} catch {
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function writeFallback(dir, secrets) {
|
|
54
|
+
writePrivateFile(fallbackPath(dir), JSON.stringify(normalizedSecrets(secrets), null, 2) + "\n");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function powershell(script, input) {
|
|
58
|
+
let lastError;
|
|
59
|
+
for (const command of ["powershell.exe", "pwsh.exe", "pwsh"]) {
|
|
60
|
+
try {
|
|
61
|
+
return execFileSync(command, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
|
|
62
|
+
input,
|
|
63
|
+
encoding: "utf8",
|
|
64
|
+
windowsHide: true,
|
|
65
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
66
|
+
});
|
|
67
|
+
} catch (error) {
|
|
68
|
+
lastError = error;
|
|
69
|
+
if (error?.code !== "ENOENT") break;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
throw lastError || new Error("powershell_unavailable");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function writeDpapi(dir, secrets) {
|
|
76
|
+
const plain = JSON.stringify(normalizedSecrets(secrets));
|
|
77
|
+
const script = [
|
|
78
|
+
"Add-Type -AssemblyName System.Security",
|
|
79
|
+
"$value=[Console]::In.ReadToEnd()",
|
|
80
|
+
"$bytes=[Text.Encoding]::UTF8.GetBytes($value)",
|
|
81
|
+
"$protected=[Security.Cryptography.ProtectedData]::Protect($bytes,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser)",
|
|
82
|
+
"[Console]::Out.Write([Convert]::ToBase64String($protected))",
|
|
83
|
+
].join("; ");
|
|
84
|
+
const encrypted = powershell(script, plain).trim();
|
|
85
|
+
if (!encrypted) throw new Error("dpapi_encrypt_failed");
|
|
86
|
+
writePrivateFile(dpapiPath(dir), encrypted + "\n");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function readDpapi(dir) {
|
|
90
|
+
const file = dpapiPath(dir);
|
|
91
|
+
if (!fs.existsSync(file)) return {};
|
|
92
|
+
const encrypted = fs.readFileSync(file, "utf8").trim();
|
|
93
|
+
if (!encrypted) return {};
|
|
94
|
+
const script = [
|
|
95
|
+
"Add-Type -AssemblyName System.Security",
|
|
96
|
+
"$value=[Console]::In.ReadToEnd().Trim()",
|
|
97
|
+
"$bytes=[Convert]::FromBase64String($value)",
|
|
98
|
+
"$plain=[Security.Cryptography.ProtectedData]::Unprotect($bytes,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser)",
|
|
99
|
+
"[Console]::Out.Write([Text.Encoding]::UTF8.GetString($plain))",
|
|
100
|
+
].join("; ");
|
|
101
|
+
const decoded = powershell(script, encrypted);
|
|
102
|
+
return normalizedSecrets(JSON.parse(decoded));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function keychainRead(key) {
|
|
106
|
+
try {
|
|
107
|
+
return execFileSync("security", [
|
|
108
|
+
"find-generic-password",
|
|
109
|
+
"-s", KEYCHAIN_SERVICE,
|
|
110
|
+
"-a", key,
|
|
111
|
+
"-w",
|
|
112
|
+
], {
|
|
113
|
+
encoding: "utf8",
|
|
114
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
115
|
+
}).trim();
|
|
116
|
+
} catch {
|
|
117
|
+
return "";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function keychainDelete(key) {
|
|
122
|
+
try {
|
|
123
|
+
execFileSync("security", [
|
|
124
|
+
"delete-generic-password",
|
|
125
|
+
"-s", KEYCHAIN_SERVICE,
|
|
126
|
+
"-a", key,
|
|
127
|
+
], {
|
|
128
|
+
stdio: "ignore",
|
|
129
|
+
});
|
|
130
|
+
} catch {}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function readKeychain() {
|
|
134
|
+
const result = {};
|
|
135
|
+
for (const key of SECRET_KEYS) {
|
|
136
|
+
const value = keychainRead(key);
|
|
137
|
+
if (value) result[key] = value;
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function writeKeychain(secrets) {
|
|
143
|
+
const normalized = normalizedSecrets(secrets);
|
|
144
|
+
for (const key of SECRET_KEYS) {
|
|
145
|
+
const value = normalized[key];
|
|
146
|
+
if (!value) {
|
|
147
|
+
keychainDelete(key);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
execFileSync("security", [
|
|
151
|
+
"add-generic-password",
|
|
152
|
+
"-U",
|
|
153
|
+
"-s", KEYCHAIN_SERVICE,
|
|
154
|
+
"-a", key,
|
|
155
|
+
"-w", value,
|
|
156
|
+
], {
|
|
157
|
+
stdio: "ignore",
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function hasSecrets(value) {
|
|
163
|
+
return SECRET_KEYS.some((key) => typeof value?.[key] === "string" && value[key].length > 0);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function readSecrets(dir, options = {}) {
|
|
167
|
+
const store = resolveStore(options);
|
|
168
|
+
try {
|
|
169
|
+
if (store === "keychain") {
|
|
170
|
+
const secrets = readKeychain();
|
|
171
|
+
if (hasSecrets(secrets)) return secrets;
|
|
172
|
+
} else if (store === "dpapi") {
|
|
173
|
+
const secrets = readDpapi(dir);
|
|
174
|
+
if (hasSecrets(secrets)) return secrets;
|
|
175
|
+
} else {
|
|
176
|
+
return readFallback(dir);
|
|
177
|
+
}
|
|
178
|
+
} catch {}
|
|
179
|
+
|
|
180
|
+
return readFallback(dir);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function writeSecrets(dir, secrets, options = {}) {
|
|
184
|
+
const normalized = normalizedSecrets(secrets);
|
|
185
|
+
const store = resolveStore(options);
|
|
186
|
+
|
|
187
|
+
if (store === "keychain") {
|
|
188
|
+
try {
|
|
189
|
+
writeKeychain(normalized);
|
|
190
|
+
removeFile(fallbackPath(dir));
|
|
191
|
+
removeFile(dpapiPath(dir));
|
|
192
|
+
return "keychain";
|
|
193
|
+
} catch {}
|
|
194
|
+
} else if (store === "dpapi") {
|
|
195
|
+
try {
|
|
196
|
+
writeDpapi(dir, normalized);
|
|
197
|
+
removeFile(fallbackPath(dir));
|
|
198
|
+
return "dpapi";
|
|
199
|
+
} catch {}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
writeFallback(dir, normalized);
|
|
203
|
+
return "file";
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function clearSecrets(dir, options = {}) {
|
|
207
|
+
removeFile(fallbackPath(dir));
|
|
208
|
+
removeFile(dpapiPath(dir));
|
|
209
|
+
|
|
210
|
+
const store = resolveStore(options);
|
|
211
|
+
if (store === "keychain" || process.platform === "darwin") {
|
|
212
|
+
for (const key of SECRET_KEYS) keychainDelete(key);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function secretStorePaths(dir) {
|
|
217
|
+
return {
|
|
218
|
+
fallback: fallbackPath(dir),
|
|
219
|
+
dpapi: dpapiPath(dir),
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export { resolveStore as resolveSecretStore };
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export const CHAT_RELAY_PACKAGE = "@anusornneal/chat-relay@latest";
|
|
4
|
+
export const UPGRADE_LOOP_GUARD_ENV = "CHAT_RELAY_UPGRADE_GUARD_UNTIL";
|
|
5
|
+
export const UPGRADE_LOOP_GUARD_MS = 60_000;
|
|
6
|
+
|
|
7
|
+
function uiArgs(options = {}) {
|
|
8
|
+
if (options.tuiEnabled === true) return ["--tui"];
|
|
9
|
+
if (options.tuiEnabled === false) return ["--plain"];
|
|
10
|
+
return [];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function windowsCommand(args) {
|
|
14
|
+
return ["npx", "-y", CHAT_RELAY_PACKAGE, "remote", ...args]
|
|
15
|
+
.map((part) => (/^[A-Za-z0-9_@./:-]+$/.test(part) ? part : `"${String(part).replaceAll('"', '\\"')}"`))
|
|
16
|
+
.join(" ");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createUpgradeRelaunchSpec(options = {}, {
|
|
20
|
+
platform = process.platform,
|
|
21
|
+
env = process.env,
|
|
22
|
+
now = Date.now(),
|
|
23
|
+
} = {}) {
|
|
24
|
+
const guardUntil = Number(env?.[UPGRADE_LOOP_GUARD_ENV]) || 0;
|
|
25
|
+
if (guardUntil > now) {
|
|
26
|
+
return {
|
|
27
|
+
ok: false,
|
|
28
|
+
error: "upgrade_loop_guard",
|
|
29
|
+
retryAt: new Date(guardUntil).toISOString(),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const args = uiArgs(options);
|
|
34
|
+
const childEnv = {
|
|
35
|
+
...env,
|
|
36
|
+
[UPGRADE_LOOP_GUARD_ENV]: String(now + UPGRADE_LOOP_GUARD_MS),
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
if (platform === "win32") {
|
|
40
|
+
return {
|
|
41
|
+
ok: true,
|
|
42
|
+
command: env?.ComSpec || "cmd.exe",
|
|
43
|
+
args: ["/d", "/s", "/c", windowsCommand(args)],
|
|
44
|
+
options: {
|
|
45
|
+
env: childEnv,
|
|
46
|
+
stdio: "inherit",
|
|
47
|
+
windowsHide: false,
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
ok: true,
|
|
54
|
+
command: "npx",
|
|
55
|
+
args: ["-y", CHAT_RELAY_PACKAGE, "remote", ...args],
|
|
56
|
+
options: {
|
|
57
|
+
env: childEnv,
|
|
58
|
+
stdio: "inherit",
|
|
59
|
+
windowsHide: false,
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function launchLatestRemote(options = {}, {
|
|
65
|
+
spawnImpl = spawn,
|
|
66
|
+
platform = process.platform,
|
|
67
|
+
env = process.env,
|
|
68
|
+
now = Date.now(),
|
|
69
|
+
} = {}) {
|
|
70
|
+
const spec = createUpgradeRelaunchSpec(options, { platform, env, now });
|
|
71
|
+
if (!spec.ok) return spec;
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const child = spawnImpl(spec.command, spec.args, spec.options);
|
|
75
|
+
child?.unref?.();
|
|
76
|
+
return {
|
|
77
|
+
ok: true,
|
|
78
|
+
pid: Number.isInteger(child?.pid) ? child.pid : null,
|
|
79
|
+
package: CHAT_RELAY_PACKAGE,
|
|
80
|
+
};
|
|
81
|
+
} catch (error) {
|
|
82
|
+
return {
|
|
83
|
+
ok: false,
|
|
84
|
+
error: "upgrade_relaunch_failed",
|
|
85
|
+
message: error instanceof Error ? error.message : String(error),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
}
|