cctether 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +35 -2
- package/bin/cctether.js +7 -0
- package/package.json +42 -4
- package/src/check.js +108 -0
- package/src/cli.js +273 -0
- package/src/config.js +158 -0
- package/src/control.js +114 -0
- package/src/daemon.js +134 -0
- package/src/gateway.js +410 -0
- package/src/log.js +4 -0
- package/src/mcp.js +145 -0
- package/src/pairing.js +29 -0
- package/src/protocol.js +107 -0
- package/src/ratelimit.js +59 -0
- package/src/schema.js +56 -0
- package/src/setup.js +634 -0
- package/src/shim.js +122 -0
- package/src/system.js +294 -0
- package/src/text.js +291 -0
- package/src/tools.js +329 -0
package/src/shim.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// `cctether mcp`: what MCP clients run. Connects stdin/stdout to the resident service's control
|
|
2
|
+
// socket, starting the service if it isn't running (D11). If the service restarts, the shim
|
|
3
|
+
// reconnects; calls that were in flight get an error instead of hanging.
|
|
4
|
+
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { openSync, closeSync, mkdirSync, statSync, renameSync, chmodSync } from 'node:fs';
|
|
7
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
8
|
+
import { paths } from './config.js';
|
|
9
|
+
import { connectSocket } from './control.js';
|
|
10
|
+
import { createMcpSession, lineSplitter } from './mcp.js';
|
|
11
|
+
|
|
12
|
+
const PREAMBLE = JSON.stringify({ cctether: 1, mode: 'mcp' }) + '\n';
|
|
13
|
+
const LOG_MAX = 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
export function spawnDaemon(P, cliPath, env = process.env, extraArgs = []) {
|
|
16
|
+
mkdirSync(P.dir, { recursive: true, mode: 0o700 });
|
|
17
|
+
try {
|
|
18
|
+
if (statSync(P.log).size > LOG_MAX) renameSync(P.log, P.log + '.1');
|
|
19
|
+
} catch {}
|
|
20
|
+
const fd = openSync(P.log, 'a', 0o600);
|
|
21
|
+
try { chmodSync(P.log, 0o600); } catch {}
|
|
22
|
+
const child = spawn(process.execPath, [cliPath, 'daemon', ...extraArgs], {
|
|
23
|
+
detached: true,
|
|
24
|
+
stdio: ['ignore', fd, fd],
|
|
25
|
+
env,
|
|
26
|
+
});
|
|
27
|
+
child.unref();
|
|
28
|
+
closeSync(fd);
|
|
29
|
+
return child.pid;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Connect to the service, starting it if needed. Resolves a socket or null. */
|
|
33
|
+
export async function connectOrStart(P, cliPath, { waitMs = 6000 } = {}) {
|
|
34
|
+
let s = await connectSocket(P.socket, 1000);
|
|
35
|
+
if (s) return s;
|
|
36
|
+
spawnDaemon(P, cliPath);
|
|
37
|
+
const deadline = Date.now() + waitMs;
|
|
38
|
+
while (Date.now() < deadline) {
|
|
39
|
+
await sleep(100);
|
|
40
|
+
s = await connectSocket(P.socket, 1000);
|
|
41
|
+
if (s) return s;
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function runShim({ dir, version, cliPath, stdin = process.stdin, stdout = process.stdout }) {
|
|
47
|
+
const P = paths(dir);
|
|
48
|
+
const writeOut = (line) => stdout.write(line + '\n');
|
|
49
|
+
|
|
50
|
+
let sock = await connectOrStart(P, cliPath);
|
|
51
|
+
if (!sock) {
|
|
52
|
+
// Fallback: answer MCP ourselves so the client gets a useful message instead of a dead server.
|
|
53
|
+
const session = createMcpSession({
|
|
54
|
+
write: writeOut,
|
|
55
|
+
browser: null,
|
|
56
|
+
version,
|
|
57
|
+
unavailable: `The cctether service could not be started. Ask the user to run \`cctether daemon\` in a terminal on this computer to see the error (log: ${P.log}).`,
|
|
58
|
+
});
|
|
59
|
+
stdin.setEncoding('utf8');
|
|
60
|
+
stdin.on('data', lineSplitter((l) => session.handleLine(l)));
|
|
61
|
+
stdin.on('end', () => process.exit(0));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const pending = new Map(); // JSON id → method
|
|
66
|
+
let queue = [];
|
|
67
|
+
let connected = false;
|
|
68
|
+
let closing = false;
|
|
69
|
+
|
|
70
|
+
const attach = (s) => {
|
|
71
|
+
sock = s;
|
|
72
|
+
connected = true;
|
|
73
|
+
s.setEncoding('utf8');
|
|
74
|
+
s.write(PREAMBLE);
|
|
75
|
+
for (const l of queue) s.write(l + '\n');
|
|
76
|
+
queue = [];
|
|
77
|
+
s.on('data', lineSplitter((line) => {
|
|
78
|
+
try {
|
|
79
|
+
const m = JSON.parse(line);
|
|
80
|
+
if (m && 'id' in m && !('method' in m)) pending.delete(JSON.stringify(m.id));
|
|
81
|
+
} catch {}
|
|
82
|
+
writeOut(line);
|
|
83
|
+
}));
|
|
84
|
+
s.on('error', () => {});
|
|
85
|
+
s.on('close', () => onSocketClosed());
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
async function onSocketClosed() {
|
|
89
|
+
connected = false;
|
|
90
|
+
if (closing) return;
|
|
91
|
+
for (const [idJson, method] of pending) {
|
|
92
|
+
const id = JSON.parse(idJson);
|
|
93
|
+
const text = 'The cctether service restarted while this call was running. Try again.';
|
|
94
|
+
writeOut(JSON.stringify(method === 'tools/call'
|
|
95
|
+
? { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }], isError: true } }
|
|
96
|
+
: { jsonrpc: '2.0', id, error: { code: -32603, message: text } }));
|
|
97
|
+
}
|
|
98
|
+
pending.clear();
|
|
99
|
+
for (let attempt = 0; !closing; attempt++) {
|
|
100
|
+
const s = await connectOrStart(P, cliPath);
|
|
101
|
+
if (s) return attach(s);
|
|
102
|
+
await sleep(Math.min(1000 * 2 ** attempt, 15000));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
attach(sock);
|
|
107
|
+
stdin.setEncoding('utf8');
|
|
108
|
+
stdin.on('data', lineSplitter((line) => {
|
|
109
|
+
if (!line.trim()) return;
|
|
110
|
+
try {
|
|
111
|
+
const m = JSON.parse(line);
|
|
112
|
+
if (m && typeof m.method === 'string' && 'id' in m && m.id !== null) pending.set(JSON.stringify(m.id), m.method);
|
|
113
|
+
} catch {}
|
|
114
|
+
if (connected) sock.write(line + '\n');
|
|
115
|
+
else queue.push(line);
|
|
116
|
+
}));
|
|
117
|
+
stdin.on('end', () => {
|
|
118
|
+
closing = true;
|
|
119
|
+
sock?.end();
|
|
120
|
+
setTimeout(() => process.exit(0), 200).unref();
|
|
121
|
+
});
|
|
122
|
+
}
|
package/src/system.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// What `cctether setup` needs to know about this computer (SPEC §8.1): where cctether is installed,
|
|
2
|
+
// npm, systemd user services, and Claude Code's MCP registration. Every outside command goes through
|
|
3
|
+
// `run` so tests can fake it.
|
|
4
|
+
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { homedir, userInfo } from 'node:os';
|
|
8
|
+
import { delimiter, dirname, join, sep } from 'node:path';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Run a program. Never throws.
|
|
12
|
+
* @returns {{ status: number|null, stdout: string, stderr: string, error?: Error }}
|
|
13
|
+
*/
|
|
14
|
+
export function run(cmd, args = [], { timeoutMs = 60_000, inherit = false, env } = {}) {
|
|
15
|
+
const r = spawnSync(cmd, args, {
|
|
16
|
+
encoding: 'utf8',
|
|
17
|
+
timeout: timeoutMs,
|
|
18
|
+
stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
|
19
|
+
env: env ?? process.env,
|
|
20
|
+
});
|
|
21
|
+
return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '', error: r.error };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** True for folders npx puts on PATH (its temporary cache, or a project's node_modules/.bin). */
|
|
25
|
+
export function isNpxDir(d) {
|
|
26
|
+
const parts = d.split(sep);
|
|
27
|
+
return parts.includes('_npx') || (parts.at(-1) === '.bin' && parts.at(-2) === 'node_modules');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Find a program on PATH. With skipNpx, folders that npx added are ignored. */
|
|
31
|
+
export function findOnPath(name, env = process.env, { skipNpx = false } = {}) {
|
|
32
|
+
for (const d of (env.PATH ?? '').split(delimiter)) {
|
|
33
|
+
if (!d || (skipNpx && isNpxDir(d))) continue;
|
|
34
|
+
const p = join(d, name);
|
|
35
|
+
try {
|
|
36
|
+
if (statSync(p).isFile()) {
|
|
37
|
+
accessSync(p, constants.X_OK);
|
|
38
|
+
return p;
|
|
39
|
+
}
|
|
40
|
+
} catch {}
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function realpath(p) {
|
|
46
|
+
try { return realpathSync(p); } catch { return null; }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The version of the cctether package that a bin path or cli path belongs to. */
|
|
50
|
+
export function versionAt(path) {
|
|
51
|
+
const real = realpath(path);
|
|
52
|
+
if (!real) return null;
|
|
53
|
+
try {
|
|
54
|
+
const pkg = JSON.parse(readFileSync(join(dirname(dirname(real)), 'package.json'), 'utf8'));
|
|
55
|
+
return pkg.name === 'cctether' ? pkg.version : null;
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function npmGlobalPrefix(runFn = run) {
|
|
62
|
+
const r = runFn('npm', ['prefix', '-g'], { timeoutMs: 30_000 });
|
|
63
|
+
const p = r.status === 0 ? r.stdout.trim() : '';
|
|
64
|
+
return p || null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Can this user install into npm's global folder? */
|
|
68
|
+
export function npmPrefixWritable(prefix) {
|
|
69
|
+
const target = existsSync(join(prefix, 'lib', 'node_modules')) ? join(prefix, 'lib', 'node_modules') : prefix;
|
|
70
|
+
try {
|
|
71
|
+
accessSync(target, constants.W_OK);
|
|
72
|
+
return true;
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Where is the running cctether?
|
|
80
|
+
* - installed: a normal npm install; `binPath` is the `cctether` command (onPath: whether PATH finds it)
|
|
81
|
+
* - npx: inside npm's temporary npx cache, which may be cleaned up at any time
|
|
82
|
+
* - checkout: some other folder, e.g. a git checkout run with `node server/bin/cctether.js`
|
|
83
|
+
*/
|
|
84
|
+
export function locateSelf({ cliPath, env = process.env, runFn = run }) {
|
|
85
|
+
const real = realpath(cliPath) ?? cliPath;
|
|
86
|
+
if (real.split(sep).includes('_npx')) return { kind: 'npx', cliPath: real };
|
|
87
|
+
const onPath = findOnPath('cctether', env);
|
|
88
|
+
if (onPath && realpath(onPath) === real) return { kind: 'installed', binPath: onPath, cliPath: real, onPath: true };
|
|
89
|
+
const prefix = npmGlobalPrefix(runFn);
|
|
90
|
+
if (prefix) {
|
|
91
|
+
const bin = join(prefix, 'bin', 'cctether');
|
|
92
|
+
if (realpath(bin) === real) return { kind: 'installed', binPath: bin, cliPath: real, onPath: false };
|
|
93
|
+
}
|
|
94
|
+
return { kind: 'checkout', cliPath: real };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The command line MCP clients should run: [command, ...args]. */
|
|
98
|
+
export function mcpCommand(self, nodePath = process.execPath) {
|
|
99
|
+
return self.kind === 'installed' ? [self.binPath, 'mcp'] : [nodePath, self.cliPath, 'mcp'];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// --- Claude Code ---------------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
export function claudeConfigFile(env = process.env) {
|
|
105
|
+
return env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, '.claude.json') : join(homedir(), '.claude.json');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The user-scope "cctether" MCP server Claude Code already has, read from its config file.
|
|
110
|
+
* @returns {{ command: string, args: string[], env: object } | null | undefined} undefined = can't tell
|
|
111
|
+
*/
|
|
112
|
+
export function claudeRegistration(env = process.env) {
|
|
113
|
+
let cfg;
|
|
114
|
+
try {
|
|
115
|
+
cfg = JSON.parse(readFileSync(claudeConfigFile(env), 'utf8'));
|
|
116
|
+
} catch (e) {
|
|
117
|
+
return e.code === 'ENOENT' ? null : undefined;
|
|
118
|
+
}
|
|
119
|
+
const s = cfg?.mcpServers?.cctether;
|
|
120
|
+
if (!s) return null;
|
|
121
|
+
if (typeof s.command !== 'string') return undefined;
|
|
122
|
+
return { command: s.command, args: Array.isArray(s.args) ? s.args : [], env: s.env ?? {} };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Claude Code's personal instructions file (its "user memory"), read by every session. */
|
|
126
|
+
export function claudeMdFile(env = process.env) {
|
|
127
|
+
return env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, 'CLAUDE.md') : join(homedir(), '.claude', 'CLAUDE.md');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const MD_START_LINE = /^<!-- cctether:start\b.*-->\s*$/;
|
|
131
|
+
const MD_END_LINE = /^<!-- cctether:end -->\s*$/;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Where the cctether note is in CLAUDE.md text. Markers only count as whole lines, and only one
|
|
135
|
+
* start line followed by one end line is a note; anything else is left alone ('ambiguous').
|
|
136
|
+
* @returns {{ state: 'absent'|'present'|'empty'|'ambiguous', lines: string[], eol: string, start?: number, end?: number }}
|
|
137
|
+
*/
|
|
138
|
+
export function findClaudeMdNote(text) {
|
|
139
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n';
|
|
140
|
+
const lines = text.split(/\r?\n/);
|
|
141
|
+
const starts = [];
|
|
142
|
+
const ends = [];
|
|
143
|
+
lines.forEach((l, i) => {
|
|
144
|
+
if (MD_START_LINE.test(l)) starts.push(i);
|
|
145
|
+
else if (MD_END_LINE.test(l)) ends.push(i);
|
|
146
|
+
});
|
|
147
|
+
if (!starts.length && !ends.length) return { state: 'absent', lines, eol };
|
|
148
|
+
if (starts.length !== 1 || ends.length !== 1 || ends[0] < starts[0]) return { state: 'ambiguous', lines, eol };
|
|
149
|
+
const [start] = starts;
|
|
150
|
+
const [end] = ends;
|
|
151
|
+
const inside = lines.slice(start + 1, end).some((l) => l.trim());
|
|
152
|
+
// A block someone emptied means "no thanks": it is only filled again when asked to.
|
|
153
|
+
return { state: inside ? 'present' : 'empty', lines, eol, start, end };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Read CLAUDE.md as text; '' if it doesn't exist. Throws if it isn't valid UTF-8 (we'd damage it). */
|
|
157
|
+
export function readClaudeMd(path) {
|
|
158
|
+
let buf;
|
|
159
|
+
try {
|
|
160
|
+
buf = readFileSync(path);
|
|
161
|
+
} catch (e) {
|
|
162
|
+
if (e.code === 'ENOENT') return '';
|
|
163
|
+
throw e;
|
|
164
|
+
}
|
|
165
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(buf);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Add or refresh the marked cctether note in CLAUDE.md, keeping everything else exactly as it is.
|
|
170
|
+
* Written in place (not via a temporary file), so a symlink, hard links and the file's permissions
|
|
171
|
+
* stay as they were, and a read-only file fails instead of being replaced.
|
|
172
|
+
* @returns {'added'|'updated'|'same'|'ambiguous'|'optedOut'}
|
|
173
|
+
*/
|
|
174
|
+
export function upsertClaudeMdNote(path, body, comment, { force = false } = {}) {
|
|
175
|
+
const text = readClaudeMd(path);
|
|
176
|
+
const note = findClaudeMdNote(text);
|
|
177
|
+
if (note.state === 'ambiguous') return 'ambiguous';
|
|
178
|
+
if (note.state === 'empty' && !force) return 'optedOut';
|
|
179
|
+
const block = [`<!-- cctether:start ${comment} -->`, ...body.trim().split('\n'), '<!-- cctether:end -->'];
|
|
180
|
+
let lines;
|
|
181
|
+
let result;
|
|
182
|
+
if (note.state === 'absent') {
|
|
183
|
+
lines = text ? [...note.lines] : [];
|
|
184
|
+
while (lines.length && !lines.at(-1).trim()) lines.pop();
|
|
185
|
+
if (lines.length) lines.push('');
|
|
186
|
+
lines.push(...block, '');
|
|
187
|
+
result = 'added';
|
|
188
|
+
} else {
|
|
189
|
+
lines = [...note.lines.slice(0, note.start), ...block, ...note.lines.slice(note.end + 1)];
|
|
190
|
+
result = 'updated';
|
|
191
|
+
}
|
|
192
|
+
const next = lines.join(note.eol);
|
|
193
|
+
if (next === text) return 'same';
|
|
194
|
+
if (!text) mkdirSync(dirname(path), { recursive: true });
|
|
195
|
+
writeFileSync(path, next);
|
|
196
|
+
return result;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// --- systemd -------------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
export const UNIT_NAME = 'cctether';
|
|
202
|
+
export const UNIT_HEADER = '# Written by `cctether setup`. Run it again to update this file.';
|
|
203
|
+
|
|
204
|
+
export function systemdUserAvailable(runFn = run) {
|
|
205
|
+
const r = runFn('systemctl', ['--user', 'show-environment'], { timeoutMs: 15_000 });
|
|
206
|
+
return r.status === 0;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function unitFile(env = process.env) {
|
|
210
|
+
const base = env.XDG_CONFIG_HOME || join(homedir(), '.config');
|
|
211
|
+
return join(base, 'systemd', 'user', `${UNIT_NAME}.service`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export class UnitError extends Error {}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Quote one word for a systemd unit file: quotes, backslashes and % specifiers everywhere, and $
|
|
218
|
+
* variables only on Exec lines (elsewhere $ has no special meaning). Control characters such as a
|
|
219
|
+
* newline can't be written safely, so such paths are refused.
|
|
220
|
+
*/
|
|
221
|
+
export function sdQuote(s, { exec = false } = {}) {
|
|
222
|
+
s = String(s);
|
|
223
|
+
if (/[\x00-\x1f\x7f]/.test(s)) throw new UnitError(`a path contains a control character: ${JSON.stringify(s)}`);
|
|
224
|
+
let q = s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%');
|
|
225
|
+
if (exec) q = q.replace(/\$/g, '$$$$');
|
|
226
|
+
return `"${q}"`;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The config folder a unit file's service uses, if it says so (CCTETHER_HOME), else null. */
|
|
230
|
+
export function unitConfigDir(content) {
|
|
231
|
+
const m = /^Environment="CCTETHER_HOME=((?:[^"\\]|\\.)*)"$/m.exec(content ?? '');
|
|
232
|
+
return m ? m[1].replace(/%%/g, '%').replace(/\\(.)/g, '$1') : null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* The service unit. `sandbox` adds systemd's file-system protection: everything read-only except
|
|
237
|
+
* the config folder. Some systems don't allow it for user services; setup then retries without.
|
|
238
|
+
*/
|
|
239
|
+
export function renderUnit({ nodePath, cliPath, configDir, socketPath, sandbox = true }) {
|
|
240
|
+
const rw = [configDir];
|
|
241
|
+
if (socketPath && !socketPath.startsWith(configDir + sep)) rw.push(dirname(socketPath));
|
|
242
|
+
const lines = [
|
|
243
|
+
UNIT_HEADER,
|
|
244
|
+
'[Unit]',
|
|
245
|
+
'Description=cctether: browser tools for Claude Code',
|
|
246
|
+
'After=network.target',
|
|
247
|
+
'',
|
|
248
|
+
'[Service]',
|
|
249
|
+
'Type=exec',
|
|
250
|
+
// --takeover: if Claude Code already started a copy, this one replaces it (see daemon.js).
|
|
251
|
+
`ExecStart=${sdQuote(nodePath, { exec: true })} ${sdQuote(cliPath, { exec: true })} daemon --takeover`,
|
|
252
|
+
// Always explicit: the service must use the same folder (and key) as this setup run.
|
|
253
|
+
`Environment=${sdQuote(`CCTETHER_HOME=${configDir}`)}`,
|
|
254
|
+
'Restart=always',
|
|
255
|
+
'RestartSec=2',
|
|
256
|
+
'NoNewPrivileges=yes',
|
|
257
|
+
...(sandbox ? ['PrivateTmp=yes', 'ProtectSystem=strict', `ReadWritePaths=${rw.map(sdQuote).join(' ')}`] : []),
|
|
258
|
+
'',
|
|
259
|
+
'[Install]',
|
|
260
|
+
'WantedBy=default.target',
|
|
261
|
+
'',
|
|
262
|
+
];
|
|
263
|
+
return lines.join('\n');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function serviceActive(runFn = run) {
|
|
267
|
+
const r = runFn('systemctl', ['--user', 'is-active', UNIT_NAME], { timeoutMs: 15_000 });
|
|
268
|
+
return r.stdout.trim() === 'active';
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The service's main process ID according to systemd, or null. */
|
|
272
|
+
export function serviceMainPid(runFn = run) {
|
|
273
|
+
const r = runFn('systemctl', ['--user', 'show', UNIT_NAME, '-p', 'MainPID', '--value'], { timeoutMs: 15_000 });
|
|
274
|
+
const n = Number(r.stdout.trim());
|
|
275
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Exit status of the service's last start: 226 means systemd couldn't set up the sandbox. */
|
|
279
|
+
export function serviceExitStatus(runFn = run) {
|
|
280
|
+
const r = runFn('systemctl', ['--user', 'show', UNIT_NAME, '-p', 'ExecMainStatus', '--value'], { timeoutMs: 15_000 });
|
|
281
|
+
const n = Number(r.stdout.trim());
|
|
282
|
+
return Number.isInteger(n) ? n : null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export function lingerEnabled(runFn = run, user = userInfo().username) {
|
|
286
|
+
const r = runFn('loginctl', ['show-user', user, '-p', 'Linger', '--value'], { timeoutMs: 15_000 });
|
|
287
|
+
return r.status === 0 && r.stdout.trim() === 'yes';
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Try to turn on linger without sudo (works where polkit allows it for yourself). */
|
|
291
|
+
export function tryEnableLinger(runFn = run) {
|
|
292
|
+
const r = runFn('loginctl', ['--no-ask-password', 'enable-linger'], { timeoutMs: 15_000 });
|
|
293
|
+
return r.status === 0;
|
|
294
|
+
}
|