ccdeck 3.82.4 → 4.0.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/LICENSING.md +42 -4
- package/README.md +183 -72
- package/THIRD_PARTY_NOTICES.md +243 -17
- package/bin/cli/tui.js +58 -4
- package/bin/deck.js +27 -1
- package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
- package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
- package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
- package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
- package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
- package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
- package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
- package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
- package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
- package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
- package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
- package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
- package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
- package/dist/web/assets/app-40gNTTfq.js +361 -0
- package/dist/web/assets/app-BRjYF6oD.css +1 -0
- package/dist/web/assets/{index-B-l-VxLm.js → index-XIY3yFiN.js} +1 -1
- package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
- package/dist/web/assets/screens-9_ivqfcF.js +12 -0
- package/dist/web/assets/screens-DUniTTbC.css +1 -0
- package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
- package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
- package/dist/web/assets/xterm-4jYizCpg.js +27 -0
- package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
- package/dist/web/index.html +16 -6
- package/package.json +13 -1
- package/release-notes.json +67 -0
- package/src/server/account-client.mjs +196 -0
- package/src/server/account-connect.mjs +238 -0
- package/src/server/account-flag.mjs +106 -0
- package/src/server/account-projects.mjs +1 -1
- package/src/server/account-service.mjs +532 -0
- package/src/server/account-status.mjs +293 -0
- package/src/server/account-store.mjs +137 -0
- package/src/server/account-sync.mjs +473 -0
- package/src/server/account-token-store.mjs +216 -0
- package/src/server/account-ui-fields.mjs +126 -0
- package/src/server/account-watch.mjs +1 -1
- package/src/server/browser-watch-log.mjs +1 -1
- package/src/server/browser-watch-store.mjs +1 -1
- package/src/server/ccdeck-account-routes.mjs +252 -0
- package/src/server/ccusage-install.mjs +2 -2
- package/src/server/ccusage-registry.mjs +4 -4
- package/src/server/ccusage-session.mjs +11 -0
- package/src/server/claude-accounts.mjs +1 -1
- package/src/server/claude-recovery.mjs +9 -4
- package/src/server/claude-settings-catalog.mjs +6 -6
- package/src/server/claude-settings.mjs +1 -1
- package/src/server/codex-auto.mjs +1 -1
- package/src/server/codex-cost-usage.mjs +7 -2
- package/src/server/codex-live-checkpoint.mjs +24 -9
- package/src/server/codex-live-engine.mjs +14 -4
- package/src/server/codex-live-handoff.mjs +53 -9
- package/src/server/codex-names.mjs +49 -0
- package/src/server/codex-translate.mjs +1 -1
- package/src/server/codex-ultrafast.d.mts +3 -0
- package/src/server/codex-ultrafast.mjs +5 -0
- package/src/server/codex-watch.mjs +25 -0
- package/src/server/command-panel-engine.mjs +300 -0
- package/src/server/command-panel-platform.mjs +99 -0
- package/src/server/cswap-auto-choice.mjs +1 -1
- package/src/server/cswap-auto-loop.mjs +1 -1
- package/src/server/cswap-install.mjs +21 -40
- package/src/server/deck-home.mjs +6 -0
- package/src/server/deck-prefs.mjs +53 -1
- package/src/server/detach.mjs +1 -1
- package/src/server/engine-download.mjs +277 -0
- package/src/server/engine-install.mjs +378 -0
- package/src/server/engine-package.mjs +267 -0
- package/src/server/event-log.mjs +7 -1
- package/src/server/event-pipeline.mjs +29 -1
- package/src/server/ghostty-handoff.mjs +81 -0
- package/src/server/index.mjs +143 -5
- package/src/server/installer.mjs +4 -1
- package/src/server/integrations/jira-write-guard.mjs +14 -208
- package/src/server/integrations/store.mjs +37 -19
- package/src/server/integrations/write-guard.mjs +223 -0
- package/src/server/intel-cpu-temperature.mjs +26 -0
- package/src/server/lifecycle.mjs +69 -6
- package/src/server/log-replay.mjs +4 -0
- package/src/server/login-service.mjs +7 -1
- package/src/server/macmon.mjs +1 -1
- package/src/server/npm-latest.mjs +1 -1
- package/src/server/org-telemetry.mjs +1 -1
- package/src/server/output-watch.mjs +4 -1
- package/src/server/panel-provenance.mjs +390 -0
- package/src/server/pinned-build.mjs +14 -0
- package/src/server/prefs-refusal.mjs +8 -1
- package/src/server/prefs-routes.mjs +60 -11
- package/src/server/pro-engine-client.mjs +339 -0
- package/src/server/pro-engine-install.mjs +294 -0
- package/src/server/pro-engine-terminal.mjs +308 -0
- package/src/server/project-discovery.mjs +139 -0
- package/src/server/provider-session-name.mjs +58 -0
- package/src/server/quota-closes.mjs +1 -1
- package/src/server/quota-history.mjs +1 -1
- package/src/server/reports.mjs +86 -21
- package/src/server/request-gates.mjs +34 -5
- package/src/server/restart-note.mjs +1 -1
- package/src/server/seed-boundary.mjs +489 -0
- package/src/server/session-counts.mjs +244 -0
- package/src/server/session-deck-names.mjs +143 -0
- package/src/server/session-enrichment.mjs +43 -6
- package/src/server/session-name-route.mjs +73 -0
- package/src/server/session-summary.mjs +12 -1
- package/src/server/session-transcript-routes.mjs +167 -0
- package/src/server/swap-log.mjs +1 -1
- package/src/server/system-metrics.mjs +57 -0
- package/src/server/terminal-bridge.mjs +485 -0
- package/src/server/terminal-folder.mjs +61 -0
- package/src/server/terminal-js-routes.mjs +752 -0
- package/src/server/terminal-routes.mjs +553 -0
- package/src/server/terminal-sessions.mjs +759 -0
- package/src/server/terminal-socket.mjs +403 -0
- package/src/server/terminal-target.mjs +928 -0
- package/src/server/thermal-metrics.mjs +13 -9
- package/src/server/tmux-control.mjs +1319 -0
- package/src/server/tmux-download.mjs +220 -0
- package/src/server/tmux.mjs +542 -0
- package/src/server/token-redact.mjs +42 -3
- package/src/server/tool-audit-report.mjs +44 -6
- package/src/server/tool-audit-routes.mjs +12 -1
- package/src/server/tool-audit.mjs +42 -8
- package/src/server/traffic-radar-monitor.mjs +1 -1
- package/src/server/traffic-radar-permission.mjs +1 -1
- package/src/server/transcript-gate.mjs +1 -1
- package/src/server/transcript-scan.mjs +15 -7
- package/src/server/transcript-turns.mjs +154 -0
- package/src/server/tui-network.mjs +1 -0
- package/src/server/tui-view.mjs +28 -0
- package/src/server/utf8-carry.mjs +159 -0
- package/src/server/uv-bootstrap.mjs +2 -2
- package/src/server/windows-acl.mjs +158 -0
- package/src/server/ws-frames.mjs +690 -0
- package/dist/web/assets/BrowserWatchModal-CWVooKxD.js +0 -1
- package/dist/web/assets/IntegrationModal-DLX43RIK.js +0 -7
- package/dist/web/assets/RadioPanel-Cj6PjrvQ.js +0 -1
- package/dist/web/assets/TrafficRadar-Bq1YcuHB.js +0 -8
- package/dist/web/assets/UsageHistoryModal-CMSCca5_.js +0 -1
- package/dist/web/assets/app-BHxsMz3-.js +0 -358
- package/dist/web/assets/app-CbXmr9rC.css +0 -1
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// Minimal host transport. Native session algorithms live in the private engine.
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { EventEmitter } from 'node:events';
|
|
5
|
+
import { ENGINE_PROTOCOL, ENGINE_MAX_FRAME, verifyEngineInstallation } from './pro-engine-install.mjs';
|
|
6
|
+
|
|
7
|
+
const fail = (code, message = 'The terminal engine is unavailable.') => Object.assign(new Error(message), { code });
|
|
8
|
+
const MAX_PENDING = 32;
|
|
9
|
+
const MAX_WRITE_QUEUE = 4 * 1024 * 1024;
|
|
10
|
+
// Terminal streams (docs/contracts/pro-engine-host-v1.md): ids per engine
|
|
11
|
+
// instance; one input message at most what ws-frames lets a browser send
|
|
12
|
+
// (DEFAULT_MAX_MESSAGE_BYTES); one joined output message and one control
|
|
13
|
+
// object at most what the engine may send.
|
|
14
|
+
const MAX_STREAM_ID = 0xffff_ffff;
|
|
15
|
+
const MAX_INPUT_BYTES = 1024 * 1024;
|
|
16
|
+
const MAX_JOINED_BYTES = 64 * 1024 * 1024;
|
|
17
|
+
const MAX_CONTROL_BYTES = 4096;
|
|
18
|
+
const CLOSE_CODES = new Set([1000, 1001, 1011]);
|
|
19
|
+
const HANDLE = /^[0-9a-f]{64}$/;
|
|
20
|
+
// A lone UTF-16 surrogate has no UTF-8 form: JSON.stringify writes it as an
|
|
21
|
+
// escape the engine's parser refuses as malformed, which ends the IPC and
|
|
22
|
+
// every request on it. No JSON on the wire carries one.
|
|
23
|
+
const LONE_SURROGATE = /\p{Cs}/u;
|
|
24
|
+
const wellFormed = (key, value) => { if (LONE_SURROGATE.test(key) || (typeof value === 'string' && LONE_SURROGATE.test(value))) throw fail('invalid_request'); return value; };
|
|
25
|
+
const replaceLoneSurrogates = text => text.replace(/\p{Cs}/gu, '\ufffd');
|
|
26
|
+
/** The variable that lets an engine serve the Command Panel's terminal
|
|
27
|
+
* (docs/contracts/pro-engine-host-v1.md, "Terminal opt-in"). */
|
|
28
|
+
export const TERMINAL_OPT_IN = 'CCDECK_ENGINE_TERMINAL';
|
|
29
|
+
/**
|
|
30
|
+
* The engine's environment: `env` without TERMINAL_OPT_IN, in any case, so a
|
|
31
|
+
* value the deck inherited from its shell never reaches an engine; then set to
|
|
32
|
+
* exactly "1" for an engine started for the Command Panel (`terminal`), and
|
|
33
|
+
* for no other.
|
|
34
|
+
*/
|
|
35
|
+
export function engineEnv(env, terminal) {
|
|
36
|
+
const out = {};
|
|
37
|
+
for (const [key, value] of Object.entries(env)) if (key.toUpperCase() !== TERMINAL_OPT_IN) out[key] = value;
|
|
38
|
+
if (terminal === true) out[TERMINAL_OPT_IN] = '1';
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
function awaitStartup(starting, signal, timeoutMs) {
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
const clean = () => { clearTimeout(timer); signal?.removeEventListener('abort', abort); };
|
|
44
|
+
const abort = () => { clean(); reject(fail('cancelled', 'The operation was cancelled.')); };
|
|
45
|
+
const timer = setTimeout(() => { clean(); reject(fail('timeout')); }, timeoutMs); timer.unref();
|
|
46
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
47
|
+
starting.then(value => { clean(); resolve(value); }, error => { clean(); reject(error); });
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
const isCount = value => Number.isSafeInteger(value) && value >= 0;
|
|
51
|
+
/** The engine's one control object in a kind-3 payload, or null for anything
|
|
52
|
+
* that is not exactly `credit` or `close`: not UTF-8 JSON, an unknown `t`, a
|
|
53
|
+
* field missing, unknown, repeated (JSON.parse keeps the last of two) or of
|
|
54
|
+
* the wrong type, a close code the bridge never sends, or a reason over the
|
|
55
|
+
* 123 bytes a close frame has room for. */
|
|
56
|
+
function engineControl(payload) {
|
|
57
|
+
if (payload.length > MAX_CONTROL_BYTES) return null;
|
|
58
|
+
let text, message;
|
|
59
|
+
try { text = new TextDecoder('utf-8', { fatal: true }).decode(payload); message = JSON.parse(text); } catch { return null; }
|
|
60
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) return null;
|
|
61
|
+
const keys = Object.keys(message), spelled = text.match(/"(?:[^"\\]|\\.)*"\s*:/g)?.length ?? 0;
|
|
62
|
+
if (spelled !== keys.length) return null;
|
|
63
|
+
const fields = keys.sort().join(',');
|
|
64
|
+
if (message.t === 'credit') return fields === 'bytes,t' && isCount(message.bytes) ? message : null;
|
|
65
|
+
if (message.t === 'close') return fields === 'code,reason,t' && CLOSE_CODES.has(message.code) && typeof message.reason === 'string' && Buffer.byteLength(message.reason) <= 123 ? message : null;
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const ALLOWED = /^terminal\.[a-zA-Z][a-zA-Z0-9.]{0,63}$/;
|
|
69
|
+
export class ProEngineClient extends EventEmitter {
|
|
70
|
+
#child; #starting; #installation; #nonce; #pending = new Map(); #out = 0n; #in = 0n; #id = 0;
|
|
71
|
+
#prefix = Buffer.alloc(4); #prefixAt = 0; #body; #bodyAt = 0;
|
|
72
|
+
#closed = false; #heartbeat; #failures = 0; #retryAt = 0; #generation = 0; #capabilities;
|
|
73
|
+
#streams = new Map(); #lastStream = 0; #verify;
|
|
74
|
+
/** `verifyInstallation`, the second argument, is for the Windows preview's
|
|
75
|
+
* test-only client alone (in the preview folder beside the package, which
|
|
76
|
+
* the package does not ship): the deck builds its clients through createProEngineClient,
|
|
77
|
+
* which takes one argument, so every client of the deck verifies with
|
|
78
|
+
* verifyEngineInstallation and the keys it was given. */
|
|
79
|
+
constructor({ enabled = false, directory, publicKey, minimumVersion, hostVersion = '0.0.0', timeoutMs = 10_000, heartbeatMs = 15_000, terminal = false } = {}, { verifyInstallation = verifyEngineInstallation } = {}) {
|
|
80
|
+
super(); this.options = Object.freeze({ enabled, directory, publicKey, minimumVersion, hostVersion, timeoutMs, heartbeatMs, terminal: terminal === true });
|
|
81
|
+
this.#verify = verifyInstallation;
|
|
82
|
+
}
|
|
83
|
+
get enabled() { return this.options.enabled === true; }
|
|
84
|
+
get capabilities() { return this.#capabilities; }
|
|
85
|
+
get running() { return !!this.#child && !!this.#capabilities; }
|
|
86
|
+
async start() {
|
|
87
|
+
if (!this.enabled) throw fail('disabled');
|
|
88
|
+
if (this.#closed) throw fail('closed');
|
|
89
|
+
if (this.running) return this.#capabilities;
|
|
90
|
+
if (this.#starting) return this.#starting;
|
|
91
|
+
if (Date.now() < this.#retryAt) throw fail('backoff');
|
|
92
|
+
const starting = this.#launch(); this.#starting = starting;
|
|
93
|
+
try { return await starting; } finally { if (this.#starting === starting) this.#starting = undefined; }
|
|
94
|
+
}
|
|
95
|
+
async #launch() {
|
|
96
|
+
const installation = await awaitStartup(this.#verify(this.options), undefined, 5000);
|
|
97
|
+
if (this.#closed) throw fail('closed');
|
|
98
|
+
const child = spawn(installation.executable, [], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, shell: false, env: engineEnv(process.env, this.options.terminal) });
|
|
99
|
+
this.#child = child; this.#installation = installation; this.#nonce = randomBytes(32).toString('hex');
|
|
100
|
+
const generation = ++this.#generation;
|
|
101
|
+
// Stream ids start again at 1 for every engine instance.
|
|
102
|
+
this.#out = 0n; this.#in = 0n; this.#prefixAt = 0; this.#body = undefined; this.#bodyAt = 0; this.#lastStream = 0;
|
|
103
|
+
child.stdout.on('data', chunk => { if (generation === this.#generation) { try { this.#consume(chunk); } catch { this.#lost(child, fail('protocol')); } } });
|
|
104
|
+
// Drain without exposing untrusted stderr (which can contain paths/secrets).
|
|
105
|
+
child.stderr.on('data', () => {});
|
|
106
|
+
child.stdin.on('error', () => this.#lost(child, fail('transport')));
|
|
107
|
+
child.on('error', () => this.#lost(child, fail('startup')));
|
|
108
|
+
child.on('exit', () => this.#lost(child, fail('exited')));
|
|
109
|
+
try {
|
|
110
|
+
const caps = await this.#send('system.hello', { protocol: ENGINE_PROTOCOL, hostPid: process.pid, hostVersion: this.options.hostVersion, nonce: this.#nonce }, { timeoutMs: 5000 }, false);
|
|
111
|
+
if (!caps || caps.protocol !== ENGINE_PROTOCOL || caps.target !== installation.target || caps.buildDigest !== installation.digest || caps.engineVersion !== installation.version || !/^[0-9a-f-]{36}$/.test(caps.engineInstance ?? '') || caps.maxFrameBytes !== ENGINE_MAX_FRAME || caps.maxPending !== MAX_PENDING || caps.streamWindowBytes !== 512 * 1024 || !caps.terminal || typeof caps.terminal !== 'object' || !['unavailable', 'tmux', 'conpty'].includes(caps.terminal.backend) || ['launch', 'resume', 'attachOwned', 'attachExternalTmux', 'attachExternalConsole', 'surviveEngineRestart'].some(key => typeof caps.terminal[key] !== 'boolean')) throw fail('incompatible');
|
|
112
|
+
if (child !== this.#child || this.#closed) throw fail('exited');
|
|
113
|
+
this.#capabilities = Object.freeze({ ...caps, terminal: Object.freeze({ ...caps.terminal }) });
|
|
114
|
+
this.#failures = 0;
|
|
115
|
+
this.#heartbeat = setInterval(() => { if (this.#pending.size < MAX_PENDING) this.#send('system.ping', {}, { timeoutMs: 5000 }).catch(() => this.#lost(child, fail('heartbeat'))); }, this.options.heartbeatMs);
|
|
116
|
+
this.#heartbeat.unref(); return this.#capabilities;
|
|
117
|
+
} catch (error) { this.#lost(child, error); throw error; }
|
|
118
|
+
}
|
|
119
|
+
async request(method, params = {}, options = {}) {
|
|
120
|
+
// An attach opens a stream, which only attachTerminal registers.
|
|
121
|
+
if (!ALLOWED.test(method) || method === 'terminal.attach') throw fail('unknown_method');
|
|
122
|
+
if (options.signal?.aborted) throw fail('cancelled', 'The operation was cancelled.');
|
|
123
|
+
const timeoutMs = options.timeoutMs ?? this.options.timeoutMs;
|
|
124
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 120_000) throw fail('invalid_request');
|
|
125
|
+
const deadline = performance.now() + timeoutMs;
|
|
126
|
+
await awaitStartup(this.start(), options.signal, timeoutMs);
|
|
127
|
+
const remaining = deadline - performance.now();
|
|
128
|
+
if (remaining <= 0) throw fail('timeout');
|
|
129
|
+
return this.#send(method, params, { ...options, timeoutMs: remaining });
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Attach a terminal stream for `handle`, the 64 hex characters an engine
|
|
133
|
+
* route answered in a ticket's place. The stream id is registered before the
|
|
134
|
+
* request is written, so what the engine sends on it after its answer is
|
|
135
|
+
* kept for `start`. Never starts the engine: a handle belongs to the
|
|
136
|
+
* instance that is running. Answers the stream, or rejects with the engine's
|
|
137
|
+
* refusal (`bad_params`, `busy`, `unavailable`, `invalid_handle`) or the
|
|
138
|
+
* transport's code; a deadline or an abort gives the attach up and tells the
|
|
139
|
+
* engine with `close`.
|
|
140
|
+
*/
|
|
141
|
+
async attachTerminal(handle, { signal, timeoutMs = this.options.timeoutMs } = {}) {
|
|
142
|
+
if (!this.running || this.#capabilities.terminal.backend === 'unavailable') throw fail('unavailable');
|
|
143
|
+
if (typeof handle !== 'string' || !HANDLE.test(handle)) throw fail('bad_params');
|
|
144
|
+
if (signal?.aborted) throw fail('cancelled', 'The operation was cancelled.');
|
|
145
|
+
if (this.#lastStream >= MAX_STREAM_ID) throw fail('busy');
|
|
146
|
+
const child = this.#child;
|
|
147
|
+
const stream = { id: ++this.#lastStream, sink: undefined, held: [], parts: [], partBytes: 0, relayed: 0, sent: 0, credit: 0, input: [], paused: false, ended: false, lost: false };
|
|
148
|
+
this.#streams.set(stream.id, stream);
|
|
149
|
+
let data;
|
|
150
|
+
try { data = await this.#send('terminal.attach', { handle, stream: stream.id }, { signal, timeoutMs, attach: true }); } catch (error) {
|
|
151
|
+
// Given up: the engine may attach it yet, so it is told. Refused or gone:
|
|
152
|
+
// the id stays named, and anything that arrives for it is discarded.
|
|
153
|
+
if (error.code === 'timeout' || error.code === 'cancelled') this.#closeStream(stream); else this.#forget(stream);
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
if (!data || typeof data !== 'object' || Object.keys(data).join() !== 'stream' || data.stream !== stream.id) { this.#lost(child, fail('protocol')); throw fail('protocol'); }
|
|
157
|
+
return Object.freeze({
|
|
158
|
+
id: stream.id,
|
|
159
|
+
/** Relay to `sink` ({ binary, text, close, lost, buffered, resume }): what arrived before it first, in order. */
|
|
160
|
+
start: sink => this.#start(stream, sink),
|
|
161
|
+
/** A browser message; false when it is held for the input window, and the socket should stop being read until `resume`. */
|
|
162
|
+
send: (type, bytes) => this.#input(stream, type, bytes),
|
|
163
|
+
/** The socket drained: report it. */
|
|
164
|
+
flow: () => this.#flow(stream),
|
|
165
|
+
/** The socket went away, or the host gives the stream up. */
|
|
166
|
+
close: () => this.#closeStream(stream),
|
|
167
|
+
/** closeOpenTerminals for this stream; false when it is no longer live. */
|
|
168
|
+
shutdown: (reason, text) => this.#shutdownStream(stream, reason, text),
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
#send(method, params, { signal, timeoutMs = this.options.timeoutMs, attach = false } = {}, authenticated = true) {
|
|
172
|
+
if (!this.#child || this.#closed) return Promise.reject(fail('exited'));
|
|
173
|
+
// An attach is answered at once and is not counted by the engine either;
|
|
174
|
+
// MAX_TERMINALS bounds how many can be waiting.
|
|
175
|
+
if (!attach && this.#pending.size >= MAX_PENDING) return Promise.reject(fail('busy'));
|
|
176
|
+
if (signal?.aborted) return Promise.reject(fail('cancelled', 'The operation was cancelled.'));
|
|
177
|
+
const id = `r${++this.#id}`;
|
|
178
|
+
let payload;
|
|
179
|
+
try { payload = Buffer.from(JSON.stringify({ id, method, params, ...(authenticated ? { auth: this.#nonce } : {}) }, wellFormed)); } catch { return Promise.reject(fail('invalid_request')); }
|
|
180
|
+
if (payload.length > ENGINE_MAX_FRAME - 13 || this.#child.stdin.writableLength + payload.length + 17 > MAX_WRITE_QUEUE) return Promise.reject(fail('busy'));
|
|
181
|
+
const body = Buffer.allocUnsafe(payload.length + 17); body.writeUInt32BE(payload.length + 13); body[4] = 0; body.writeUInt32BE(0, 5); body.writeBigUInt64BE(++this.#out, 9); payload.copy(body, 17);
|
|
182
|
+
const child = this.#child;
|
|
183
|
+
return new Promise((resolve, reject) => {
|
|
184
|
+
const clean = () => { clearTimeout(timer); signal?.removeEventListener('abort', abort); this.#pending.delete(id); };
|
|
185
|
+
// An attach given up is closed on its stream instead (attachTerminal): cancelling it would answer nothing.
|
|
186
|
+
const cancel = code => { if (!this.#pending.has(id)) return; clean(); reject(fail(code, code === 'cancelled' ? 'The operation was cancelled.' : undefined)); if (authenticated && method !== 'system.cancel' && !attach) this.#send('system.cancel', { id }, { timeoutMs: 1000 }).catch(() => this.#lost(child, fail('cancellation_failed'))); };
|
|
187
|
+
const abort = () => cancel('cancelled');
|
|
188
|
+
const timer = setTimeout(() => cancel('timeout'), timeoutMs); timer.unref();
|
|
189
|
+
this.#pending.set(id, { resolve: value => { clean(); resolve(value); }, reject: error => { clean(); reject(error); } });
|
|
190
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
191
|
+
child.stdin.write(body, error => { if (error) this.#lost(child, fail('transport')); });
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
/** One stream frame, on the sequence counter every kind shares. */
|
|
195
|
+
#frame(kind, id, payload) {
|
|
196
|
+
const child = this.#child;
|
|
197
|
+
const body = Buffer.allocUnsafe(payload.length + 17); body.writeUInt32BE(payload.length + 13); body[4] = kind; body.writeUInt32BE(id, 5); body.writeBigUInt64BE(++this.#out, 9); payload.copy(body, 17);
|
|
198
|
+
child.stdin.write(body, error => { if (error) this.#lost(child, fail('transport')); });
|
|
199
|
+
}
|
|
200
|
+
#control(id, message) { this.#frame(3, id, Buffer.from(JSON.stringify(message, wellFormed))); }
|
|
201
|
+
#consume(chunk) {
|
|
202
|
+
let offset = 0; const flows = new Set();
|
|
203
|
+
while (offset < chunk.length) {
|
|
204
|
+
if (!this.#body) {
|
|
205
|
+
const count = Math.min(4 - this.#prefixAt, chunk.length - offset); chunk.copy(this.#prefix, this.#prefixAt, offset, offset + count); this.#prefixAt += count; offset += count;
|
|
206
|
+
if (this.#prefixAt < 4) continue;
|
|
207
|
+
const length = this.#prefix.readUInt32BE(); this.#prefixAt = 0;
|
|
208
|
+
if (length < 13 || length > ENGINE_MAX_FRAME) throw fail('protocol');
|
|
209
|
+
this.#body = Buffer.allocUnsafe(length); this.#bodyAt = 0;
|
|
210
|
+
}
|
|
211
|
+
const count = Math.min(this.#body.length - this.#bodyAt, chunk.length - offset); chunk.copy(this.#body, this.#bodyAt, offset, offset + count); this.#bodyAt += count; offset += count;
|
|
212
|
+
if (this.#bodyAt < this.#body.length) continue;
|
|
213
|
+
const frame = this.#body; this.#body = undefined;
|
|
214
|
+
if (frame.readBigUInt64BE(5) !== ++this.#in) throw fail('protocol');
|
|
215
|
+
if (frame[0] !== 0 || frame.readUInt32BE(1) !== 0) { this.#streamFrame(frame[0], frame.readUInt32BE(1), frame.subarray(13), flows); continue; }
|
|
216
|
+
const reply = JSON.parse(frame.subarray(13).toString('utf8'));
|
|
217
|
+
if (!reply || typeof reply.id !== 'string' || typeof reply.ok !== 'boolean' || (reply.ok ? !Object.hasOwn(reply, 'data') : !reply.error || typeof reply.error.code !== 'string')) throw fail('protocol');
|
|
218
|
+
const pending = this.#pending.get(reply.id);
|
|
219
|
+
// Timed-out/cancelled requests can have an already-in-flight final reply.
|
|
220
|
+
if (pending) { if (reply.ok) pending.resolve(reply.data); else pending.reject(fail(reply.error.code, 'The terminal operation could not be completed.')); }
|
|
221
|
+
}
|
|
222
|
+
// One flow per stream per chunk, once that stream's data in it is relayed.
|
|
223
|
+
for (const stream of flows) this.#flow(stream);
|
|
224
|
+
}
|
|
225
|
+
/** Kinds 1–4 on a nonzero stream; anything else is a violation, as is an id
|
|
226
|
+
* never allocated. An allocated id that is not live (refused, given up,
|
|
227
|
+
* closed) has its frames discarded: they crossed its close. */
|
|
228
|
+
#streamFrame(kind, id, payload, flows) {
|
|
229
|
+
if (kind < 1 || kind > 4 || id === 0 || id > this.#lastStream) throw fail('protocol');
|
|
230
|
+
const stream = this.#streams.get(id);
|
|
231
|
+
if (!stream || stream.ended) return;
|
|
232
|
+
if (kind === 4) {
|
|
233
|
+
// A part of a binary message that continues: never empty, and the whole never over the cap.
|
|
234
|
+
if (!payload.length || stream.partBytes + payload.length > MAX_JOINED_BYTES) throw fail('protocol');
|
|
235
|
+
stream.parts.push(payload); stream.partBytes += payload.length; return;
|
|
236
|
+
}
|
|
237
|
+
if (stream.parts.length && kind !== 1) throw fail('protocol');
|
|
238
|
+
if (kind === 3) {
|
|
239
|
+
const message = engineControl(payload);
|
|
240
|
+
if (!message) throw fail('protocol');
|
|
241
|
+
if (message.t === 'close') { stream.ended = true; return this.#deliver(stream, 'close', message, flows); }
|
|
242
|
+
// Credit is cumulative: never backwards, never past what was sent.
|
|
243
|
+
if (message.bytes < stream.credit || message.bytes > stream.sent) throw fail('protocol');
|
|
244
|
+
stream.credit = message.bytes; return this.#sendInput(stream);
|
|
245
|
+
}
|
|
246
|
+
let bytes = payload;
|
|
247
|
+
if (stream.parts.length) {
|
|
248
|
+
if (stream.partBytes + payload.length > MAX_JOINED_BYTES) throw fail('protocol');
|
|
249
|
+
bytes = Buffer.concat([...stream.parts, payload], stream.partBytes + payload.length); stream.parts = []; stream.partBytes = 0;
|
|
250
|
+
}
|
|
251
|
+
this.#deliver(stream, kind === 1 ? 'binary' : 'text', bytes, flows);
|
|
252
|
+
}
|
|
253
|
+
#deliver(stream, type, value, flows) {
|
|
254
|
+
if (!stream.sink) return void stream.held.push([type, value]);
|
|
255
|
+
this.#relay(stream, type, value);
|
|
256
|
+
if (type !== 'close') flows.add(stream);
|
|
257
|
+
}
|
|
258
|
+
#relay(stream, type, value) {
|
|
259
|
+
try { if (type === 'close') stream.sink.close(value.code, value.reason); else stream.sink[type](value); } catch { /* a socket that cannot take it is already closing */ }
|
|
260
|
+
// Taken off the IPC once whole: handed to the socket, or dropped by one that has closed.
|
|
261
|
+
if (type === 'close') this.#forget(stream); else stream.relayed += value.length;
|
|
262
|
+
}
|
|
263
|
+
#start(stream, sink) {
|
|
264
|
+
if (stream.lost) { try { sink.lost(); } catch {} return; }
|
|
265
|
+
if (this.#streams.get(stream.id) !== stream || stream.sink) return;
|
|
266
|
+
stream.sink = sink;
|
|
267
|
+
const held = stream.held; stream.held = [];
|
|
268
|
+
for (const [type, value] of held) this.#relay(stream, type, value);
|
|
269
|
+
if (held.length) this.#flow(stream);
|
|
270
|
+
}
|
|
271
|
+
/** The input window: data may be sent while nothing is owed, or while what is
|
|
272
|
+
* owed plus it fits; otherwise it waits, with everything after it, in order. */
|
|
273
|
+
#input(stream, type, bytes) {
|
|
274
|
+
if (bytes.length > MAX_INPUT_BYTES) throw new RangeError('A terminal message is at most 1 MiB.');
|
|
275
|
+
// A stream that has ended takes nothing more; the socket's close follows.
|
|
276
|
+
if (this.#streams.get(stream.id) !== stream || stream.ended) return true;
|
|
277
|
+
stream.input.push([type === 'binary' ? 1 : 2, bytes]);
|
|
278
|
+
this.#sendInput(stream);
|
|
279
|
+
return !(stream.paused = stream.input.length > 0);
|
|
280
|
+
}
|
|
281
|
+
#sendInput(stream) {
|
|
282
|
+
while (stream.input.length) {
|
|
283
|
+
const [kind, bytes] = stream.input[0], owed = stream.sent - stream.credit;
|
|
284
|
+
if (owed !== 0 && owed + bytes.length > this.#capabilities.streamWindowBytes) return;
|
|
285
|
+
stream.input.shift(); stream.sent += bytes.length; this.#frame(kind, stream.id, bytes);
|
|
286
|
+
}
|
|
287
|
+
if (stream.paused) { stream.paused = false; try { stream.sink?.resume(); } catch {} }
|
|
288
|
+
}
|
|
289
|
+
#flow(stream) {
|
|
290
|
+
if (this.#streams.get(stream.id) !== stream || stream.ended || !stream.sink) return;
|
|
291
|
+
let buffered = 0; try { buffered = stream.sink.buffered(); } catch {}
|
|
292
|
+
this.#control(stream.id, { t: 'flow', relayed: stream.relayed, buffered: isCount(buffered) ? buffered : 0 });
|
|
293
|
+
}
|
|
294
|
+
#closeStream(stream) {
|
|
295
|
+
if (this.#streams.get(stream.id) !== stream) return;
|
|
296
|
+
this.#forget(stream);
|
|
297
|
+
// Never after the engine's own close.
|
|
298
|
+
if (!stream.ended) this.#control(stream.id, { t: 'close' });
|
|
299
|
+
}
|
|
300
|
+
#shutdownStream(stream, reason = 'server-shutdown', text) {
|
|
301
|
+
const told = typeof text === 'string' && text !== '';
|
|
302
|
+
if (typeof reason !== 'string' || !reason) throw new RangeError('Not a shutdown the engine can be sent.');
|
|
303
|
+
// The deck's own words, so the panel is still told them: a lone surrogate
|
|
304
|
+
// becomes U+FFFD, as the UTF-8 the browser receives would have it anyway.
|
|
305
|
+
reason = replaceLoneSurrogates(reason); if (told) text = replaceLoneSurrogates(text);
|
|
306
|
+
if (Buffer.byteLength(reason) > 123 || (told && Buffer.byteLength(text) > 1024)) throw new RangeError('Not a shutdown the engine can be sent.');
|
|
307
|
+
if (this.#streams.get(stream.id) !== stream || stream.ended) return false;
|
|
308
|
+
this.#control(stream.id, { t: 'shutdown', reason, ...(told ? { text } : {}) });
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
#forget(stream) { if (this.#streams.get(stream.id) === stream) this.#streams.delete(stream.id); }
|
|
312
|
+
#lost(child, error) {
|
|
313
|
+
if (!child || child !== this.#child) return;
|
|
314
|
+
this.#child = undefined; this.#capabilities = undefined; this.#nonce = undefined;
|
|
315
|
+
clearInterval(this.#heartbeat); this.#heartbeat = undefined;
|
|
316
|
+
this.#body = undefined; this.#prefixAt = 0;
|
|
317
|
+
this.#retryAt = Date.now() + Math.min(30_000, 250 * 2 ** Math.min(this.#failures++, 7));
|
|
318
|
+
for (const item of [...this.#pending.values()]) item.reject(error);
|
|
319
|
+
// Every relayed socket closes without an exit, so its panel reconnects with a new ticket.
|
|
320
|
+
const streams = [...this.#streams.values()]; this.#streams.clear();
|
|
321
|
+
for (const stream of streams) { stream.lost = true; if (stream.sink) try { stream.sink.lost(); } catch {} }
|
|
322
|
+
child.stdin.destroy(); child.stdout.destroy(); child.stderr.destroy(); child.kill();
|
|
323
|
+
// Kill only our IPC child; it owns detaching, never persistent-agent teardown.
|
|
324
|
+
this.emit('disconnected', error.code ?? 'exited');
|
|
325
|
+
}
|
|
326
|
+
async close() {
|
|
327
|
+
if (this.#closed) return;
|
|
328
|
+
if (this.#child && this.#capabilities) { try { await this.#send('system.shutdown', {}, { timeoutMs: 1000 }); } catch {} }
|
|
329
|
+
this.#closed = true;
|
|
330
|
+
const child = this.#child;
|
|
331
|
+
this.#lost(child, fail('closed'));
|
|
332
|
+
// Answered once the process has exited (and been reaped), so whoever starts the next engine never runs it beside this one.
|
|
333
|
+
if (child && child.exitCode === null && child.signalCode === null) await new Promise(resolve => child.once('exit', resolve));
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Disabled construction does no I/O, discovery, subprocess launch or download.
|
|
338
|
+
* `terminal: true` is for the Command Panel's engine alone (command-panel-engine.mjs). */
|
|
339
|
+
export function createProEngineClient(options = {}) { return new ProEngineClient(options); }
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// Optional local executable verification. No downloads or public runtime deps.
|
|
2
|
+
//
|
|
3
|
+
// TWO CALLERS, ONE SET OF RULES. verifyEngineInstallation checks the folder the
|
|
4
|
+
// engine runs from (`<deck data folder>/engine`). engine-package.mjs checks the
|
|
5
|
+
// platform package the engine arrives in before copying it there, with the
|
|
6
|
+
// same signed-manifest, size, hash and file-reading rules (the exports below),
|
|
7
|
+
// so a file is held to one standard before and after the copy.
|
|
8
|
+
//
|
|
9
|
+
// UNIX: the folder and files belong to the user (a package source may also
|
|
10
|
+
// belong to root, since a global install is often made by it), nobody else may
|
|
11
|
+
// write them, and root is refused as a user of the engine. Nobody else may
|
|
12
|
+
// write a folder above them either, since the engine is started by its path
|
|
13
|
+
// after the check; on Linux a folder only the user's own group may write is
|
|
14
|
+
// the user's alone (ownGroup).
|
|
15
|
+
//
|
|
16
|
+
// WINDOWS: the ownership and mode bits mean nothing there, so the same
|
|
17
|
+
// questions are put to an ACL reader the caller hands in (`windowsAcl`): who
|
|
18
|
+
// owns it, who may write it, whether it is a reparse point or has a second hard
|
|
19
|
+
// link, and whether this process is elevated. A caller may hand one in; without
|
|
20
|
+
// one the gate builds the deck's own (windows-acl.mjs); Windows is offered by
|
|
21
|
+
// ENGINE_ON_WINDOWS (engine-package.mjs). The rules below are written against a reader's answers and have been run against
|
|
22
|
+
// a test double and, in CI only, the real reader.
|
|
23
|
+
import { constants, promises as fs } from 'node:fs';
|
|
24
|
+
import path from 'node:path';
|
|
25
|
+
import { createHash, createPublicKey, verify } from 'node:crypto';
|
|
26
|
+
import { createWindowsAcl } from './windows-acl.mjs';
|
|
27
|
+
import { PRODUCT } from './brand.mjs';
|
|
28
|
+
|
|
29
|
+
export const ENGINE_PROTOCOL = 1;
|
|
30
|
+
export const ENGINE_MAX_FRAME = 2 * 1024 * 1024;
|
|
31
|
+
export const ENGINE_MAX_BYTES = 128 * 1024 * 1024;
|
|
32
|
+
export const ENGINE_MANIFEST_MAX = 16 * 1024;
|
|
33
|
+
export const TARGETS = {
|
|
34
|
+
'darwin-x64': 'x86_64-apple-darwin', 'darwin-arm64': 'aarch64-apple-darwin',
|
|
35
|
+
'linux-x64': 'x86_64-unknown-linux-gnu', 'linux-arm64': 'aarch64-unknown-linux-gnu',
|
|
36
|
+
'win32-x64': 'x86_64-pc-windows-msvc',
|
|
37
|
+
};
|
|
38
|
+
/** Who may not hold write access to anything the engine runs from on Windows:
|
|
39
|
+
* by the names and by the well-known identifiers Windows gives the same
|
|
40
|
+
* groups (Everyone, Authenticated Users, Users). */
|
|
41
|
+
const WINDOWS_WRITERS_REFUSED = /^(?:everyone|authenticated users|users|builtin\\users|nt authority\\authenticated users|s-1-1-0|s-1-5-11|s-1-5-32-545)$/i;
|
|
42
|
+
const invalid = () => new Error('The installed terminal engine could not be verified.');
|
|
43
|
+
|
|
44
|
+
/** The one refusal that carries a code: a folder above the engine that other
|
|
45
|
+
* accounts can change (refuseFolder). The page then says which check it was,
|
|
46
|
+
* not that the signature failed; the folder itself goes to the log alone. */
|
|
47
|
+
export const UNSAFE_FOLDER = 'unsafe-folder';
|
|
48
|
+
const folderRefused = () => Object.assign(invalid(), { code: UNSAFE_FOLDER });
|
|
49
|
+
|
|
50
|
+
/** Where Linux keeps who has which primary group, and who else is in a group. */
|
|
51
|
+
const ACCOUNT_FILES = Object.freeze({ passwd: '/etc/passwd', group: '/etc/group' });
|
|
52
|
+
|
|
53
|
+
/** The lines of an account file with `fields` fields each, comments and blank
|
|
54
|
+
* lines left out as the C library leaves them. Throws for a line these rules
|
|
55
|
+
* cannot read and for a `+` or `-` line, which pulls accounts in from NIS. */
|
|
56
|
+
async function accountRows(file, fields) {
|
|
57
|
+
const rows = [];
|
|
58
|
+
for (const raw of (await fs.readFile(file, 'utf8')).split('\n')) {
|
|
59
|
+
const line = raw.trimStart();
|
|
60
|
+
if (!line || line.startsWith('#')) continue;
|
|
61
|
+
const row = line.split(':');
|
|
62
|
+
if (row.length !== fields || /^[+-]/.test(row[0]) || !/^[0-9]+$/.test(row[2]) || (fields === 7 && !/^[0-9]+$/.test(row[3]))) throw invalid();
|
|
63
|
+
rows.push(row);
|
|
64
|
+
}
|
|
65
|
+
return rows;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Whether `gid` is the user's own group, so that a folder only it may write is
|
|
70
|
+
* a folder only the user may write. Ubuntu, Debian and Fedora make a group of
|
|
71
|
+
* the user's name for each user (useradd's USERGROUPS_ENAB) and give them a
|
|
72
|
+
* umask of 002, so the folders their programs make are 0775: the ~/.local the
|
|
73
|
+
* deck or an installer made first, a second Claude profile CLAUDE_CONFIG_DIR
|
|
74
|
+
* names. Read as "others may write", every engine under them was refused.
|
|
75
|
+
*
|
|
76
|
+
* It is the user's own only when /etc/passwd and /etc/group say so with
|
|
77
|
+
* nothing left over: it is this process's group and the primary group of the
|
|
78
|
+
* user's own entry, no other account has it as theirs or shares the user's
|
|
79
|
+
* name, and no entry for it in /etc/group names anybody else. Either file
|
|
80
|
+
* unreadable, the user or the group not in it (an account from LDAP or another
|
|
81
|
+
* directory, whose groups these files do not hold), or a line these rules
|
|
82
|
+
* cannot read, and it is not: refused as it always was. Linux only: macOS
|
|
83
|
+
* gives every user one shared group.
|
|
84
|
+
*/
|
|
85
|
+
async function ownGroup(uid, gid) {
|
|
86
|
+
if (typeof process.getgid !== 'function' || gid !== process.getgid()) return false;
|
|
87
|
+
try {
|
|
88
|
+
const [users, groups] = await Promise.all([accountRows(ACCOUNT_FILES.passwd, 7), accountRows(ACCOUNT_FILES.group, 4)]);
|
|
89
|
+
const mine = users.filter(row => Number(row[2]) === uid);
|
|
90
|
+
const names = new Set(mine.map(row => row[0]));
|
|
91
|
+
const entries = groups.filter(row => Number(row[2]) === gid);
|
|
92
|
+
return mine.length > 0 && mine.every(row => Number(row[3]) === gid)
|
|
93
|
+
&& users.every(row => (Number(row[3]) !== gid && !names.has(row[0])) || Number(row[2]) === uid)
|
|
94
|
+
&& entries.length > 0 && entries.every(row => row[3].split(',').map(name => name.trim()).every(name => !name || names.has(name)));
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Each folder the deck's log has named, so a status read every few hundred
|
|
101
|
+
// milliseconds names it once.
|
|
102
|
+
const named = new Set();
|
|
103
|
+
|
|
104
|
+
/** Refuses the engine for a folder above it that someone else may change, and
|
|
105
|
+
* says once in the deck's log which folder and what would let it run. The
|
|
106
|
+
* path goes to the log only, never to the page: a route's body is readable by
|
|
107
|
+
* a DNS-rebound page, and a path names the user. The page gets the code
|
|
108
|
+
* alone (UNSAFE_FOLDER). */
|
|
109
|
+
function refuseFolder(folder, ownedByOther) {
|
|
110
|
+
const key = `${ownedByOther ? 'owner' : 'write'} ${folder}`;
|
|
111
|
+
if (!named.has(key)) {
|
|
112
|
+
named.add(key);
|
|
113
|
+
const quoted = `'${folder.replaceAll("'", "'\\''")}'`;
|
|
114
|
+
console.error(ownedByOther
|
|
115
|
+
? `${PRODUCT}: terminal: the engine is refused: ${folder}, a folder above it, belongs to another account, which could replace it. Set CCDECK_HOME to a folder under your own.`
|
|
116
|
+
: `${PRODUCT}: terminal: the engine is refused: other accounts can write ${folder}, a folder above it, and could replace it. If nobody else should: chmod go-w ${quoted}`);
|
|
117
|
+
}
|
|
118
|
+
throw folderRefused();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* What a file or folder must be to be trusted, for `platform`. Unix asks the
|
|
123
|
+
* file's own stat; Windows asks `windowsAcl`:
|
|
124
|
+
* `identity()` -> `{ user, elevated }`, the user this process runs as;
|
|
125
|
+
* `inspect(path)` -> `{ owner, writers: [names or SIDs that may write], reparsePoint, links }`.
|
|
126
|
+
* Resolves to `{ directory(path, stat), file(path, stat, executable) }`, each
|
|
127
|
+
* throwing when the answer is no. `allowRoot` also accepts root as the owner
|
|
128
|
+
* of a Unix package source, and `allowGroupWrite` its group's write bit:
|
|
129
|
+
* npm writes a package under the user's umask, and the usual 002 leaves files
|
|
130
|
+
* 664 and folders 775. That is safe for a source only, because what is
|
|
131
|
+
* installed is the bytes read once and checked against the signed manifest,
|
|
132
|
+
* never the file as it stands later. Write by others is refused either way.
|
|
133
|
+
*/
|
|
134
|
+
export async function trustGate({ platform = process.platform, windowsAcl, allowRoot = false, allowGroupWrite = false, uid } = {}) {
|
|
135
|
+
if (platform === 'win32') {
|
|
136
|
+
windowsAcl ??= createWindowsAcl();
|
|
137
|
+
if (typeof windowsAcl.identity !== 'function' || typeof windowsAcl.inspect !== 'function') throw invalid();
|
|
138
|
+
const me = await windowsAcl.identity();
|
|
139
|
+
if (!me || me.elevated !== false || typeof me.user !== 'string' || !me.user) throw invalid();
|
|
140
|
+
const check = async (target, stat, isFile) => {
|
|
141
|
+
const info = await windowsAcl.inspect(target);
|
|
142
|
+
if (!info || info.owner !== me.user || info.reparsePoint !== false || !Array.isArray(info.writers)) throw invalid();
|
|
143
|
+
if (info.writers.some(name => WINDOWS_WRITERS_REFUSED.test(String(name)))) throw invalid();
|
|
144
|
+
if (isFile && (info.links !== 1 || (stat.nlink ?? 1) > 1)) throw invalid();
|
|
145
|
+
};
|
|
146
|
+
return { directory: (target, stat) => check(target, stat, false), file: (target, stat) => check(target, stat, true) };
|
|
147
|
+
}
|
|
148
|
+
const me = uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
|
|
149
|
+
if (me === undefined || me === 0) throw invalid();
|
|
150
|
+
const owners = allowRoot ? [me, 0] : [me];
|
|
151
|
+
const writers = allowGroupWrite ? 0o002 : 0o022;
|
|
152
|
+
const owned = (stat, executable) => owners.includes(stat.uid) && !(stat.mode & writers) && (!executable || !!(stat.mode & 0o100));
|
|
153
|
+
return {
|
|
154
|
+
directory: async (_target, stat) => { if (!owned(stat, false)) throw invalid(); },
|
|
155
|
+
file: async (_target, stat, executable) => { if (!owned(stat, executable)) throw invalid(); },
|
|
156
|
+
me,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Reads `file` through O_NOFOLLOW, bounded, refusing a link, a non-file, a
|
|
161
|
+
* file the gate does not trust, an empty or oversized one, and one that
|
|
162
|
+
* changed while it was read. */
|
|
163
|
+
export async function readTrusted(file, limit, gate, executable = false) {
|
|
164
|
+
const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
165
|
+
try {
|
|
166
|
+
const before = await handle.stat();
|
|
167
|
+
if (!before.isFile() || before.size > limit || before.size < 1) throw invalid();
|
|
168
|
+
await gate.file(file, before, executable);
|
|
169
|
+
// Bound reads even if a concurrent writer grows the file after fstat.
|
|
170
|
+
const buffer = Buffer.alloc(before.size + 1);
|
|
171
|
+
let offset = 0;
|
|
172
|
+
while (offset < buffer.length) {
|
|
173
|
+
const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, null);
|
|
174
|
+
if (!bytesRead) break;
|
|
175
|
+
offset += bytesRead;
|
|
176
|
+
}
|
|
177
|
+
const data = buffer.subarray(0, offset);
|
|
178
|
+
const after = await handle.stat();
|
|
179
|
+
if (data.length !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) throw invalid();
|
|
180
|
+
return { data, stat: after };
|
|
181
|
+
} finally { await handle.close(); }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The signed entry of a manifest's bytes, once its envelope, signature (by
|
|
185
|
+
* any of `keys`) and six fields are right for `target`. Throws otherwise. */
|
|
186
|
+
export function signedEntry(manifestBytes, keys, target, platform = process.platform) {
|
|
187
|
+
const manifest = JSON.parse(manifestBytes.toString('utf8'));
|
|
188
|
+
if (!manifest || Object.keys(manifest).sort().join(',') !== 'payload,signature' || typeof manifest.payload !== 'string' || typeof manifest.signature !== 'string') throw invalid();
|
|
189
|
+
const trusted = keys.map(key => createPublicKey(key));
|
|
190
|
+
if (trusted.some(key => key.asymmetricKeyType !== 'ed25519')) throw invalid();
|
|
191
|
+
const payload = Buffer.from(manifest.payload, 'base64');
|
|
192
|
+
const signature = Buffer.from(manifest.signature, 'base64');
|
|
193
|
+
if (payload.toString('base64') !== manifest.payload || signature.toString('base64') !== manifest.signature || !trusted.some(key => verify(null, payload, key, signature))) throw invalid();
|
|
194
|
+
const entry = JSON.parse(payload.toString('utf8'));
|
|
195
|
+
const name = platform === 'win32' ? /^ccdeck-pro-engine(?:-[a-zA-Z0-9.-]+)?\.exe$/ : /^ccdeck-pro-engine(?:-[a-zA-Z0-9.-]+)?$/;
|
|
196
|
+
if (!entry || Object.keys(entry).sort().join(',') !== 'file,protocol,sha256,size,target,version' || entry.protocol !== ENGINE_PROTOCOL || entry.target !== target || !/^[a-f0-9]{64}$/.test(entry.sha256) || !Number.isSafeInteger(entry.size) || entry.size < 1 || entry.size > ENGINE_MAX_BYTES || typeof entry.version !== 'string' || !/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][a-zA-Z0-9.-]+)?$/.test(entry.version) || !name.test(entry.file)) throw invalid();
|
|
197
|
+
return entry;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The version text split as SemVer 2.0 does, or an error for anything else. */
|
|
201
|
+
function parseVersion(text) {
|
|
202
|
+
const m = /^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([a-zA-Z0-9.-]+))?(?:\+[a-zA-Z0-9.-]+)?$/.exec(typeof text === 'string' ? text : '');
|
|
203
|
+
if (!m) throw invalid();
|
|
204
|
+
return { core: m.slice(1, 4).map(BigInt), pre: m[4] === undefined ? [] : m[4].split('.') };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** SemVer 2.0 precedence of two versions (-1, 0, 1), build metadata ignored.
|
|
208
|
+
* Throws for a text that is not a version, so a bad floor refuses everything. */
|
|
209
|
+
export function compareVersions(a, b) {
|
|
210
|
+
const x = parseVersion(a), y = parseVersion(b);
|
|
211
|
+
for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] < y.core[i] ? -1 : 1;
|
|
212
|
+
if (!x.pre.length || !y.pre.length) return Math.sign(y.pre.length - x.pre.length);
|
|
213
|
+
for (let i = 0; i < Math.min(x.pre.length, y.pre.length); i++) {
|
|
214
|
+
const p = x.pre[i], q = y.pre[i];
|
|
215
|
+
if (p === q) continue;
|
|
216
|
+
const pn = /^[0-9]+$/.test(p), qn = /^[0-9]+$/.test(q);
|
|
217
|
+
if (pn && qn) return BigInt(p) < BigInt(q) ? -1 : 1;
|
|
218
|
+
if (pn !== qn) return pn ? -1 : 1;
|
|
219
|
+
return p < q ? -1 : 1;
|
|
220
|
+
}
|
|
221
|
+
return Math.sign(x.pre.length - y.pre.length);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Whether the executable's header says it is for `platform` and `arch`: ELF
|
|
225
|
+
* (64-bit, little-endian) on Linux, a thin 64-bit Mach-O on macOS, a PE image
|
|
226
|
+
* on Windows, each with the machine of that arch. Anything else, a script, a
|
|
227
|
+
* universal binary or a different machine, is no. */
|
|
228
|
+
export function executableMatchesMachine(bytes, platform = process.platform, arch = process.arch) {
|
|
229
|
+
if (!Buffer.isBuffer(bytes)) return false;
|
|
230
|
+
if (platform === 'linux') {
|
|
231
|
+
const machine = { x64: 62, arm64: 183 }[arch];
|
|
232
|
+
return bytes.length >= 20 && bytes.readUInt32BE(0) === 0x7f454c46 && bytes[4] === 2 && bytes[5] === 1 && bytes.readUInt16LE(18) === machine;
|
|
233
|
+
}
|
|
234
|
+
if (platform === 'darwin') {
|
|
235
|
+
const cpu = { x64: 0x01000007, arm64: 0x0100000c }[arch];
|
|
236
|
+
return bytes.length >= 8 && bytes.readUInt32LE(0) === 0xfeedfacf && bytes.readUInt32LE(4) === cpu;
|
|
237
|
+
}
|
|
238
|
+
if (platform === 'win32') {
|
|
239
|
+
const machine = { x64: 0x8664, arm64: 0xaa64 }[arch];
|
|
240
|
+
if (bytes.length < 0x40 || bytes.readUInt16BE(0) !== 0x4d5a) return false;
|
|
241
|
+
const at = bytes.readUInt32LE(0x3c);
|
|
242
|
+
return at <= bytes.length - 6 && bytes.readUInt32BE(at) === 0x50450000 && bytes.readUInt16LE(at + 4) === machine;
|
|
243
|
+
}
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Trusted Ed25519 public keys — one, or a list any of which may have signed
|
|
248
|
+
* the manifest — from the host, never browser/request input. An empty list
|
|
249
|
+
* trusts nothing, and is refused before anything is read.
|
|
250
|
+
*
|
|
251
|
+
* `minimumVersion`, host configuration too, is the lowest engine version the
|
|
252
|
+
* host accepts: an older one, however validly signed, is refused before it
|
|
253
|
+
* runs, and a `minimumVersion` that is not a version refuses every engine.
|
|
254
|
+
* `windowsAcl` is the Windows reader described at the top; `platform` and
|
|
255
|
+
* `arch` are there for tests. */
|
|
256
|
+
export async function verifyEngineInstallation({ directory, publicKey, minimumVersion, windowsAcl, platform = process.platform, arch = process.arch }) {
|
|
257
|
+
const keys = Array.isArray(publicKey) ? publicKey : [publicKey];
|
|
258
|
+
if (keys.length === 0) throw invalid();
|
|
259
|
+
try {
|
|
260
|
+
const target = TARGETS[`${platform}-${arch}`];
|
|
261
|
+
if (!target) throw invalid();
|
|
262
|
+
const gate = await trustGate({ platform, windowsAcl });
|
|
263
|
+
const root = await fs.realpath(directory);
|
|
264
|
+
const rootStat = await fs.lstat(root);
|
|
265
|
+
if (!rootStat.isDirectory()) throw invalid();
|
|
266
|
+
await gate.directory(root, rootStat);
|
|
267
|
+
if (platform !== 'win32') {
|
|
268
|
+
if (rootStat.mode & 0o077) throw invalid();
|
|
269
|
+
// Every folder above: the user's or root's, and writable by nobody else,
|
|
270
|
+
// unless sticky (/tmp: nobody may rename what another made) or, on
|
|
271
|
+
// Linux, writable by the user's own group alone. The account files are
|
|
272
|
+
// read once, and only when a folder needs them.
|
|
273
|
+
let alone;
|
|
274
|
+
let ancestor = path.dirname(root);
|
|
275
|
+
while (true) {
|
|
276
|
+
const s = await fs.stat(ancestor);
|
|
277
|
+
if (![0, gate.me].includes(s.uid)) refuseFolder(ancestor, true);
|
|
278
|
+
if ((s.mode & 0o022) && !(s.mode & 0o1000)) {
|
|
279
|
+
if (platform !== 'linux' || (s.mode & 0o002)) refuseFolder(ancestor, false);
|
|
280
|
+
alone ??= ownGroup(gate.me, process.getgid());
|
|
281
|
+
if (s.gid !== process.getgid() || !(await alone)) refuseFolder(ancestor, false);
|
|
282
|
+
}
|
|
283
|
+
const parent = path.dirname(ancestor); if (parent === ancestor) break; ancestor = parent;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const { data: manifestBytes } = await readTrusted(path.join(root, 'manifest.json'), ENGINE_MANIFEST_MAX, gate);
|
|
287
|
+
const entry = signedEntry(manifestBytes, keys, target, platform);
|
|
288
|
+
if (minimumVersion !== undefined && compareVersions(entry.version, minimumVersion) < 0) throw invalid();
|
|
289
|
+
const executable = path.join(root, entry.file);
|
|
290
|
+
const { data, stat } = await readTrusted(executable, entry.size, gate, true);
|
|
291
|
+
if (stat.size !== entry.size || createHash('sha256').update(data).digest('hex') !== entry.sha256) throw invalid();
|
|
292
|
+
return Object.freeze({ executable, digest: entry.sha256, target, version: entry.version });
|
|
293
|
+
} catch (error) { throw error?.code === UNSAFE_FOLDER ? folderRefused() : invalid(); }
|
|
294
|
+
}
|