@tnunamak/dalan 0.6.1 → 0.7.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/CHANGELOG.md +32 -0
- package/README.md +25 -64
- package/bin/dalan.mjs +9 -0
- package/bin/dot-worker.mjs +16 -2
- package/docs/chatgpt-worker-onboarding.md +10 -14
- package/docs/claude-worker-onboarding.md +9 -8
- package/docs/codex-to-muse.md +21 -35
- package/docs/connect-chatgpt.md +10 -16
- package/docs/dalan-upgrade.md +4 -2
- package/docs/local-agent-mcp.md +24 -4
- package/docs/manual-setup.md +2 -2
- package/docs/operations.md +10 -11
- package/docs/pull-workers.md +1 -2
- package/docs/service-setup.md +99 -145
- package/docs/setup-reference.md +5 -5
- package/docs/worker-clients.md +4 -4
- package/package.json +2 -3
- package/scripts/dalan-try-selfcheck.mjs +8 -7
- package/scripts/worker-bridge-setup.mjs +91 -81
- package/src/as-store.mjs +5 -3
- package/src/as.mjs +35 -26
- package/src/auth-check.mjs +53 -0
- package/src/cli-help.mjs +20 -15
- package/src/client-approval.mjs +57 -0
- package/src/client-convenience.mjs +166 -0
- package/src/client-conveniences.json +106 -0
- package/src/client-conveniences.schema.json +97 -0
- package/src/connect-cli.mjs +5 -5
- package/src/default-home.mjs +36 -0
- package/src/follow-current.mjs +25 -0
- package/src/gozar-routes.mjs +314 -0
- package/src/redirect-policy.mjs +61 -0
- package/src/route-setting.mjs +71 -12
- package/src/server.mjs +38 -2
- package/src/service-auto-update.mjs +68 -0
- package/src/service-launchd.mjs +166 -0
- package/src/service-update-gate.mjs +20 -0
- package/src/service-update-lock.mjs +22 -0
- package/src/service-update-runtime.mjs +290 -0
- package/src/service-update.mjs +399 -0
- package/src/service.mjs +241 -58
- package/src/setup.mjs +55 -44
- package/src/try-exposure.mjs +7 -657
- package/src/try-hosted.mjs +71 -101
- package/src/try-selfcheck.mjs +15 -8
- package/src/try.mjs +9 -13
- package/scripts/lib/expose-tailscale.mjs +0 -408
- package/src/try-hosted-clients.mjs +0 -46
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { defaultPath } from './paths.mjs';
|
|
5
|
+
import { acquireUpdateLock } from './service-update-lock.mjs';
|
|
6
|
+
import { writeAtomic } from './as-files.mjs';
|
|
7
|
+
import { setUpdateAgent } from './service-launchd.mjs';
|
|
8
|
+
|
|
9
|
+
const safePath = /^[A-Za-z0-9_@+=:,./-]+$/;
|
|
10
|
+
|
|
11
|
+
export function autoUpdateUnits({ home, unit, node }) {
|
|
12
|
+
const name = unit.replace(/\.service$/, '');
|
|
13
|
+
if (!/^dalan-[a-z0-9-]+$/.test(name)) throw new Error('invalid Dalan service unit');
|
|
14
|
+
if (![home, node].every(value => path.isAbsolute(value) && safePath.test(value))) throw new Error('update units require absolute systemd-safe paths');
|
|
15
|
+
const timer = `${name}-update.timer`;
|
|
16
|
+
return { timer, files: {
|
|
17
|
+
[`${name}-update.service`]: [
|
|
18
|
+
'[Unit]', 'Description=Check and update the Dalan bridge', 'After=network-online.target', '',
|
|
19
|
+
'[Service]', 'Type=oneshot',
|
|
20
|
+
`ExecStart=${node} ${home}/current/bin/dalan.mjs service update --home ${home} --json`,
|
|
21
|
+
`Environment=PATH=${[path.dirname(node), '/usr/local/bin', '/usr/bin', '/bin'].join(':')}`,
|
|
22
|
+
'UMask=0077', 'TimeoutStartSec=20min', 'Nice=19', 'IOSchedulingClass=idle', '',
|
|
23
|
+
].join('\n'),
|
|
24
|
+
[timer]: [
|
|
25
|
+
'[Unit]', 'Description=Daily Dalan update check', '', '[Timer]', 'OnCalendar=daily',
|
|
26
|
+
'RandomizedDelaySec=1h', 'Persistent=true', '', '[Install]', 'WantedBy=timers.target', '',
|
|
27
|
+
].join('\n'),
|
|
28
|
+
} };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function setAutoUpdate({ home, enabled }, seams = {}) {
|
|
32
|
+
const platform = seams.platform ?? process.platform;
|
|
33
|
+
if (!['linux', 'darwin'].includes(platform)) throw new Error('automatic service updates need Linux with a systemd user manager or macOS with launchd');
|
|
34
|
+
if (typeof enabled !== 'boolean') throw new Error('auto-update requires on or off');
|
|
35
|
+
home = path.resolve(home);
|
|
36
|
+
if (fs.realpathSync(home) !== home) throw new Error('service home must not use a symlink');
|
|
37
|
+
const releaseLock = acquireUpdateLock(home);
|
|
38
|
+
try {
|
|
39
|
+
const config = defaultPath(home, '.config/dot-bridge');
|
|
40
|
+
const receiptFile = path.join(config, 'service-install.json');
|
|
41
|
+
const info = fs.lstatSync(receiptFile);
|
|
42
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service receipt must be a private regular file');
|
|
43
|
+
const receipt = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
|
|
44
|
+
if (receipt.home !== home || !receipt.unit_dir || !receipt.node) throw new Error('reinstall this service with the current Dalan release before enabling automatic updates');
|
|
45
|
+
if (!safePath.test(receipt.unit_dir) || !path.isAbsolute(receipt.unit_dir) || fs.realpathSync(receipt.unit_dir) !== receipt.unit_dir) throw new Error('service unit directory must be a real absolute directory');
|
|
46
|
+
if (platform === 'darwin') {
|
|
47
|
+
const agent = setUpdateAgent({ receipt, home, node: receipt.node, enabled }, seams.launchd ?? {});
|
|
48
|
+
writeAtomic(receiptFile, `${JSON.stringify({ ...receipt, auto_update: enabled }, null, 2)}\n`);
|
|
49
|
+
return { home, auto_update: enabled, timer: agent.timer };
|
|
50
|
+
}
|
|
51
|
+
const spawn = seams.spawn ?? spawnSync;
|
|
52
|
+
const run = args => {
|
|
53
|
+
const result = spawn('systemctl', ['--user', ...args], { encoding: 'utf8', env: seams.env ?? process.env, timeout: 30000, maxBuffer: 1024 * 1024 });
|
|
54
|
+
if (result.error || result.status !== 0) throw new Error(`systemctl ${args.join(' ')} failed: ${result.error?.message ?? result.stderr ?? result.status}`);
|
|
55
|
+
};
|
|
56
|
+
const { files, timer } = autoUpdateUnits(receipt);
|
|
57
|
+
// Refuse collisions before replacing either generated unit.
|
|
58
|
+
for (const [name, text] of Object.entries(files)) {
|
|
59
|
+
const file = path.join(receipt.unit_dir, name);
|
|
60
|
+
if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) throw new Error(`${file} has different contents; refusing to replace it`);
|
|
61
|
+
}
|
|
62
|
+
for (const [name, text] of Object.entries(files)) fs.writeFileSync(path.join(receipt.unit_dir, name), text, { mode: 0o644 });
|
|
63
|
+
run(['daemon-reload']);
|
|
64
|
+
run([enabled ? 'enable' : 'disable', '--now', timer]);
|
|
65
|
+
writeAtomic(receiptFile, `${JSON.stringify({ ...receipt, auto_update: enabled }, null, 2)}\n`);
|
|
66
|
+
return { home, auto_update: enabled, timer };
|
|
67
|
+
} finally { releaseLock(); }
|
|
68
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// The macOS service backend: a LaunchAgent for the bridge and a second one that runs `dalan service update` every day.
|
|
2
|
+
// Everything here is plist text (pure) plus a thin launchctl seam, so Linux tests can fake launchctl. The shape follows the agent
|
|
3
|
+
// that scripts/worker-bridge-setup.mjs already runs on macOS 26 (domain user/UID, Aqua and Background sessions, an explicit kickstart).
|
|
4
|
+
//
|
|
5
|
+
// Rules this backend keeps:
|
|
6
|
+
// - The agent runs node by absolute path. `nodePath()` in service.mjs picks the stable Homebrew or mise symlink when node is one of those, so a
|
|
7
|
+
// node upgrade keeps working; any other node is recorded as is, and a move of that binary needs `dalan service install` again.
|
|
8
|
+
// - It runs the package through the home's `current` symlink, so the updater switches versions by repointing that link and restarting.
|
|
9
|
+
// - launchd has no pre-start step, so the agent runs `dalan service recover` first in a shell, and starts the server only if that succeeds.
|
|
10
|
+
// - KeepAlive restarts after a crash or an error exit, never after a clean exit. Logs live under the service home.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
|
|
17
|
+
export const MARKER = 'Generated by dalan service install';
|
|
18
|
+
const SESSION_TYPES = ['Aqua', 'Background'];
|
|
19
|
+
const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
|
|
20
|
+
const fail = message => { throw new Error(message); };
|
|
21
|
+
|
|
22
|
+
export const launchdLabels = unit => ({ service: `org.dalan.${unit}`, update: `org.dalan.${unit}-update` });
|
|
23
|
+
export const launchAgentsDir = (env = process.env) => path.join(env.HOME || os.homedir(), 'Library', 'LaunchAgents');
|
|
24
|
+
const agentPath = (node) => [...new Set([path.dirname(node), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin'])].join(':');
|
|
25
|
+
const xml = text => String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
26
|
+
|
|
27
|
+
function assertSafe(values) {
|
|
28
|
+
for (const [label, value] of Object.entries(values)) if (!path.isAbsolute(value) || !SAFE_PATH.test(value)) fail(`${label} is not a safe absolute path for a LaunchAgent: ${JSON.stringify(value)}`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const dict = entries => ['<dict>', ...entries.flatMap(([key, value]) => [` <key>${xml(key)}</key>`, ...value.split('\n').map(line => ` ${line}`)]), '</dict>'].join('\n');
|
|
32
|
+
const str = value => `<string>${xml(value)}</string>`;
|
|
33
|
+
const arr = items => ['<array>', ...items.map(item => ` ${str(item)}`), '</array>'].join('\n');
|
|
34
|
+
const plist = (label, body) => ['<?xml version="1.0" encoding="UTF-8"?>',
|
|
35
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
36
|
+
`<!-- ${MARKER}. Remove with: dalan service uninstall -->`, '<plist version="1.0">', body, '</plist>', ''].join('\n');
|
|
37
|
+
|
|
38
|
+
export function servicePlist({ unit, node, home, port, enableWorkspace = false, enableT3 = false }) {
|
|
39
|
+
const current = path.join(home, 'current');
|
|
40
|
+
assertSafe({ home, node, current });
|
|
41
|
+
const { service } = launchdLabels(unit);
|
|
42
|
+
const env = { HOME: home, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', DALAN_BIND_HOST: '127.0.0.1', DALAN_GOZAR_SERVICE: '1', DALAN_CATALOG_PROFILE: 'stable',
|
|
43
|
+
DALAN_ENABLE_WORKSPACE: enableWorkspace ? '1' : '0', DALAN_ENABLE_T3_TOOLS: enableT3 ? '1' : '0', DALAN_PORT: String(port), PATH: agentPath(node) };
|
|
44
|
+
const start = `${node} ${current}/bin/dalan.mjs service recover --home ${home} --quiet && exec ${node} ${current}/src/server.mjs`;
|
|
45
|
+
return plist(service, dict([
|
|
46
|
+
['Label', str(service)],
|
|
47
|
+
['ProgramArguments', arr(['/bin/sh', '-c', start])],
|
|
48
|
+
['WorkingDirectory', str(current)],
|
|
49
|
+
['EnvironmentVariables', dict(Object.entries(env).map(([key, value]) => [key, str(value)]))],
|
|
50
|
+
['RunAtLoad', '<true/>'],
|
|
51
|
+
['KeepAlive', dict([['SuccessfulExit', '<false/>']])],
|
|
52
|
+
['ThrottleInterval', '<integer>5</integer>'],
|
|
53
|
+
['LimitLoadToSessionType', arr(SESSION_TYPES)],
|
|
54
|
+
['UMask', '<integer>63</integer>'],
|
|
55
|
+
['StandardOutPath', str(path.join(home, 'logs', 'bridge.out.log'))],
|
|
56
|
+
['StandardErrorPath', str(path.join(home, 'logs', 'bridge.err.log'))],
|
|
57
|
+
]));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// The update agent runs once a day at a fixed minute between 03:00 and 03:59 that depends on the home, so many installs do not call the registry together.
|
|
61
|
+
export const updateSchedule = home => ({ Hour: 3, Minute: parseInt(createHash('sha256').update(home).digest('hex').slice(0, 4), 16) % 60 });
|
|
62
|
+
|
|
63
|
+
export function updatePlist({ unit, node, home }) {
|
|
64
|
+
const current = path.join(home, 'current');
|
|
65
|
+
assertSafe({ home, node, current });
|
|
66
|
+
const { update } = launchdLabels(unit), when = updateSchedule(home);
|
|
67
|
+
return plist(update, dict([
|
|
68
|
+
['Label', str(update)],
|
|
69
|
+
['ProgramArguments', arr([node, `${current}/bin/dalan.mjs`, 'service', 'update', '--home', home, '--json'])],
|
|
70
|
+
['EnvironmentVariables', dict([['PATH', str(agentPath(node))]])],
|
|
71
|
+
['StartCalendarInterval', dict([['Hour', `<integer>${when.Hour}</integer>`], ['Minute', `<integer>${when.Minute}</integer>`]])],
|
|
72
|
+
['ProcessType', str('Background')],
|
|
73
|
+
['Nice', '<integer>19</integer>'],
|
|
74
|
+
['LowPriorityIO', '<true/>'],
|
|
75
|
+
['LimitLoadToSessionType', arr(SESSION_TYPES)],
|
|
76
|
+
['UMask', '<integer>63</integer>'],
|
|
77
|
+
['StandardOutPath', str(path.join(home, 'logs', 'update.out.log'))],
|
|
78
|
+
['StandardErrorPath', str(path.join(home, 'logs', 'update.err.log'))],
|
|
79
|
+
]));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---- launchctl --------------------------------------------------------------------------------------------------------------------------
|
|
83
|
+
export function launchctl(args, { spawn = spawnSync, env = process.env } = {}) {
|
|
84
|
+
const result = spawn('launchctl', args, { encoding: 'utf8', env, timeout: 30000, maxBuffer: 1024 * 1024 });
|
|
85
|
+
return { status: result.error ? -1 : (result.status ?? -1), stdout: result.stdout ?? '', stderr: result.error ? String(result.error.message) : (result.stderr ?? '') };
|
|
86
|
+
}
|
|
87
|
+
const uidOf = seams => (seams.uid ?? process.getuid?.());
|
|
88
|
+
const domainOf = seams => `user/${uidOf(seams)}`;
|
|
89
|
+
export const isLoaded = (label, seams = {}) => launchctl(['print', `${domainOf(seams)}/${label}`], seams).status === 0;
|
|
90
|
+
const must = (result, what) => { if (result.status !== 0) fail(`${what} failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`); };
|
|
91
|
+
|
|
92
|
+
// Load the agent from its plist, then ask launchd to start it: on macOS 26 a bootstrapped agent can stay loaded and never spawn.
|
|
93
|
+
export function loadAgent({ label, plistFile }, seams = {}) {
|
|
94
|
+
const domain = domainOf(seams);
|
|
95
|
+
if (!isLoaded(label, seams)) must(launchctl(['bootstrap', domain, plistFile], seams), `launchctl bootstrap ${domain} ${plistFile}`);
|
|
96
|
+
const kick = launchctl(['kickstart', `${domain}/${label}`], seams);
|
|
97
|
+
return { kicked: kick.status === 0, detail: kick.status === 0 ? '' : String(kick.stderr).trim() };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function unloadAgent({ label }, seams = {}) {
|
|
101
|
+
if (!isLoaded(label, seams)) return false;
|
|
102
|
+
must(launchctl(['bootout', `${domainOf(seams)}/${label}`], seams), `launchctl bootout ${label}`);
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// The updater's three actions for a launchd service. `daemon-reload` has no launchd meaning: the plist does not change on update.
|
|
107
|
+
export function controlLaunchd(receipt, action, seams = {}) {
|
|
108
|
+
const { service } = launchdLabels(receipt.unit), plistFile = path.join(receipt.unit_dir, `${service}.plist`);
|
|
109
|
+
if (action === 'daemon-reload') return;
|
|
110
|
+
if (action === 'stop') { unloadAgent({ label: service }, seams); return; }
|
|
111
|
+
if (action === 'restart') {
|
|
112
|
+
if (isLoaded(service, seams)) must(launchctl(['kickstart', '-k', `${domainOf(seams)}/${service}`], seams), `launchctl kickstart -k ${service}`);
|
|
113
|
+
else {
|
|
114
|
+
const { kicked, detail } = loadAgent({ label: service, plistFile }, seams);
|
|
115
|
+
if (!kicked) fail(`launchctl kickstart ${service} failed: ${detail}`);
|
|
116
|
+
}
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
fail('unsupported service action');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---- plist files ------------------------------------------------------------------------------------------------------------------------
|
|
123
|
+
// Write a generated plist. A plist that already has exactly this text is left alone (returns false). A different one that carries our marker
|
|
124
|
+
// is replaced; anything else is refused so a hand-made agent is never overwritten.
|
|
125
|
+
export function writeAgentFile(file, text) {
|
|
126
|
+
let existing = null;
|
|
127
|
+
try { const info = fs.lstatSync(file); if (!info.isFile() || info.isSymbolicLink()) fail(`${file} is not a regular file; refusing to replace it`); existing = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
128
|
+
if (existing === text) return false;
|
|
129
|
+
if (existing !== null && !existing.includes(MARKER)) fail(`${file} already exists and was not generated by dalan; refusing to overwrite it`);
|
|
130
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
|
|
131
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
132
|
+
fs.writeFileSync(temp, text, { mode: 0o644 });
|
|
133
|
+
fs.renameSync(temp, file);
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function lintPlist(file, { spawn = spawnSync } = {}) {
|
|
138
|
+
const result = spawn('plutil', ['-lint', file], { encoding: 'utf8' });
|
|
139
|
+
if (result.error) return null; // plutil is not installed (not macOS): not checked
|
|
140
|
+
return result.status === 0;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Turn the daily update agent on or off. Off removes the agent from launchd and deletes its plist.
|
|
144
|
+
export function setUpdateAgent({ receipt, home, node, enabled }, seams = {}) {
|
|
145
|
+
const { update } = launchdLabels(receipt.unit), file = path.join(receipt.unit_dir, `${update}.plist`);
|
|
146
|
+
if (enabled) {
|
|
147
|
+
fs.mkdirSync(path.join(home, 'logs'), { recursive: true, mode: 0o700 });
|
|
148
|
+
const changed = writeAgentFile(file, updatePlist({ unit: receipt.unit, node: receipt.node ?? node, home }));
|
|
149
|
+
if (changed) unloadAgent({ label: update }, seams);
|
|
150
|
+
if (!isLoaded(update, seams)) must(launchctl(['bootstrap', domainOf(seams), file], seams), `launchctl bootstrap ${file}`);
|
|
151
|
+
} else {
|
|
152
|
+
unloadAgent({ label: update }, seams);
|
|
153
|
+
fs.rmSync(file, { force: true });
|
|
154
|
+
}
|
|
155
|
+
return { timer: update };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function removeAgents({ unit, unit_dir: dir }, seams = {}) {
|
|
159
|
+
const { service, update } = launchdLabels(unit), removed = [];
|
|
160
|
+
for (const label of [update, service]) {
|
|
161
|
+
if (unloadAgent({ label }, seams)) removed.push(`unloaded ${label}`);
|
|
162
|
+
const file = path.join(dir, `${label}.plist`);
|
|
163
|
+
if (fs.existsSync(file)) { if (!fs.readFileSync(file, 'utf8').includes(MARKER)) fail(`${file} was not generated by dalan; leaving it`); fs.rmSync(file); removed.push(`removed ${file}`); }
|
|
164
|
+
}
|
|
165
|
+
return removed;
|
|
166
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// An update window is open from the moment the updater records phase 'switched' (service stopped, snapshot complete) until it
|
|
6
|
+
// records 'committed' or finishes a rollback and removes the journal. Rollback restores the snapshot, so any mutation the
|
|
7
|
+
// candidate acknowledged inside the window would be lost. The server therefore refuses every mutating entry while it is open.
|
|
8
|
+
// Unreadable journal: fail closed. The updater writes it atomically, so only damage reaches this branch.
|
|
9
|
+
export function updateWindowOpen(home = os.homedir()) {
|
|
10
|
+
let text;
|
|
11
|
+
try { text = fs.readFileSync(path.join(home, 'update-transaction.json'), 'utf8'); }
|
|
12
|
+
catch (error) { return error.code === 'ENOENT' || error.code === 'ENOTDIR' ? false : true; }
|
|
13
|
+
try { return JSON.parse(text)?.phase === 'switched'; } catch { return true; }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const UPDATE_RETRY_SECONDS = 15;
|
|
17
|
+
export function refuseDuringUpdate(res) {
|
|
18
|
+
res.writeHead(503, { 'content-type': 'application/json', 'retry-after': String(UPDATE_RETRY_SECONDS) });
|
|
19
|
+
res.end(JSON.stringify({ error: 'service_updating', retryable: true }));
|
|
20
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
|
|
5
|
+
// Keep the inode: deleting a lock file would let a new caller lock a different file.
|
|
6
|
+
// SQLite's exclusive lock is released by the kernel even if the updater is killed.
|
|
7
|
+
export function acquireUpdateLock(home) {
|
|
8
|
+
const file = path.join(home, 'update-lock.sqlite');
|
|
9
|
+
const fd = fs.openSync(file, 'a', 0o600);
|
|
10
|
+
fs.closeSync(fd);
|
|
11
|
+
const info = fs.lstatSync(file);
|
|
12
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service update lock must be a private regular file');
|
|
13
|
+
const db = new DatabaseSync(file);
|
|
14
|
+
try { db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE'); }
|
|
15
|
+
catch (error) { db.close(); if (error.errcode === 5 || error.errcode === 6) throw new Error('another service update is already running'); throw error; }
|
|
16
|
+
let held = true;
|
|
17
|
+
return () => {
|
|
18
|
+
if (!held) return;
|
|
19
|
+
held = false;
|
|
20
|
+
try { db.exec('ROLLBACK'); } finally { db.close(); }
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { controlLaunchd } from './service-launchd.mjs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import https from 'node:https';
|
|
7
|
+
import net from 'node:net';
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { defaultPath } from './paths.mjs';
|
|
12
|
+
import { initAsFiles } from './as-files.mjs';
|
|
13
|
+
|
|
14
|
+
const PACKAGE = '@tnunamak/dalan';
|
|
15
|
+
const PUBLIC_REGISTRY = 'https://registry.npmjs.org';
|
|
16
|
+
const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
|
|
17
|
+
const TIMEOUT = 30_000;
|
|
18
|
+
const fail = message => { throw new Error(message); };
|
|
19
|
+
const MAX_TARBALL_BYTES = 200 * 1024 * 1024;
|
|
20
|
+
|
|
21
|
+
// npm 12 refuses a remote tarball URL as a dependency (allow-remote defaults to none), so the updater fetches the tarball itself,
|
|
22
|
+
// checks every byte against the registry's sha512 integrity, and hands npm only a local file. Works the same on npm 10, 11 and 12.
|
|
23
|
+
async function fetchTarball(url, integrity, { timeout = 120_000, fetchImpl = fetch } = {}) {
|
|
24
|
+
let bytes;
|
|
25
|
+
if (/^file:\/\//.test(url)) bytes = fs.readFileSync(fileURLToPath(url));
|
|
26
|
+
else {
|
|
27
|
+
const response = await fetchImpl(url, { signal: AbortSignal.timeout(timeout) });
|
|
28
|
+
if (!response.ok) fail(`release tarball download failed (${response.status})`);
|
|
29
|
+
const length = Number(response.headers.get('content-length'));
|
|
30
|
+
if (Number.isFinite(length) && length > MAX_TARBALL_BYTES) fail('release tarball is too large');
|
|
31
|
+
bytes = Buffer.from(await response.arrayBuffer());
|
|
32
|
+
}
|
|
33
|
+
if (bytes.length > MAX_TARBALL_BYTES) fail('release tarball is too large');
|
|
34
|
+
if (`sha512-${createHash('sha512').update(bytes).digest('base64')}` !== integrity) fail('release tarball integrity does not match registry metadata');
|
|
35
|
+
return bytes;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function validRelease(value, { allowLocalTarball = false } = {}) {
|
|
39
|
+
const localTarball = typeof value?.dist?.tarball === 'string' && (/^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?\//.test(value.dist.tarball) || /^file:\/\//.test(value.dist.tarball));
|
|
40
|
+
let productionTarball = false;
|
|
41
|
+
try { const url = new URL(value?.dist?.tarball); productionTarball = url.protocol === 'https:' && url.hostname === 'registry.npmjs.org'; } catch { /* checked below */ }
|
|
42
|
+
if (!value || value.name !== PACKAGE || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value.version ?? '') ||
|
|
43
|
+
!value.dist || typeof value.dist.tarball !== 'string' || (!productionTarball && !(allowLocalTarball && localTarball)) ||
|
|
44
|
+
typeof value.dist.integrity !== 'string' || !/^sha512-[A-Za-z0-9+/]+={0,2}$/.test(value.dist.integrity)) {
|
|
45
|
+
fail('npm registry returned invalid Dalan release metadata');
|
|
46
|
+
}
|
|
47
|
+
return { name: value.name, version: value.version, dist: { tarball: value.dist.tarball, integrity: value.dist.integrity } };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function requestJson(url, { timeout = TIMEOUT, socketPath, headers = {}, allowHttp = false } = {}) {
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
let absoluteTimer, settled = false;
|
|
53
|
+
const finish = (fn, value) => {
|
|
54
|
+
if (settled) return;
|
|
55
|
+
settled = true;
|
|
56
|
+
clearTimeout(absoluteTimer);
|
|
57
|
+
fn(value);
|
|
58
|
+
};
|
|
59
|
+
const target = new URL(url);
|
|
60
|
+
const transport = target.protocol === 'https:' ? https : http;
|
|
61
|
+
if (target.protocol !== 'https:' && !socketPath && !(allowHttp && target.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(target.hostname))) return finish(reject, new Error('HTTPS required'));
|
|
62
|
+
const req = transport.request({ ...(socketPath ? { socketPath, path: url } : { hostname: target.hostname, port: target.port || undefined, path: target.pathname + target.search }), method: 'GET', headers, timeout }, res => {
|
|
63
|
+
const chunks = []; let size = 0;
|
|
64
|
+
res.on('data', chunk => { size += chunk.length; if (size > 2 * 1024 * 1024) req.destroy(new Error('response too large')); else chunks.push(chunk); });
|
|
65
|
+
res.on('aborted', () => finish(reject, new Error('response ended before completion')));
|
|
66
|
+
res.on('error', error => finish(reject, error));
|
|
67
|
+
res.on('end', () => {
|
|
68
|
+
if (res.statusCode !== 200) return finish(reject, Object.assign(new Error(`request failed (${res.statusCode})`), { statusCode: res.statusCode }));
|
|
69
|
+
try { finish(resolve, JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { finish(reject, new Error('invalid JSON response')); }
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
req.on('timeout', () => req.destroy(new Error('request timed out')));
|
|
73
|
+
req.on('error', error => finish(reject, error));
|
|
74
|
+
absoluteTimer = setTimeout(() => req.destroy(new Error('request timed out')), timeout);
|
|
75
|
+
req.end();
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function run(command, args, { cwd, env, timeout = TIMEOUT } = {}) {
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
const child = spawn(command, args, { cwd, env, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
82
|
+
let stderr = '', done = false;
|
|
83
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), timeout);
|
|
84
|
+
child.stderr.on('data', chunk => { if (stderr.length < 8192) stderr += chunk.toString().slice(0, 8192 - stderr.length); });
|
|
85
|
+
child.on('error', error => { if (done) return; done = true; clearTimeout(timer); reject(error); });
|
|
86
|
+
child.on('close', (code, signal) => { if (done) return; done = true; clearTimeout(timer); code === 0 ? resolve() : reject(new Error(`${path.basename(command)} failed (${signal || code})${stderr.trim() ? `: ${stderr.trim().slice(0, 1000)}` : ''}`)); });
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function latestRelease(_receipt, { registry = PUBLIC_REGISTRY } = {}) {
|
|
91
|
+
const localTestRegistry = /^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(registry);
|
|
92
|
+
if (!/^https:\/\//.test(registry) && !localTestRegistry) fail('npm registry must use HTTPS');
|
|
93
|
+
const metadata = await requestJson(`${registry.replace(/\/$/, '')}/@tnunamak%2fdalan/latest`, { allowHttp: localTestRegistry });
|
|
94
|
+
return validRelease(metadata, { allowLocalTarball: localTestRegistry });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function packageAt(home, version) { return path.join(home, 'versions', version, 'node_modules', '@tnunamak', 'dalan'); }
|
|
98
|
+
function installEnv(dir) {
|
|
99
|
+
const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: dir, npm_config_userconfig: path.join(dir, '.npmrc'), npm_config_cache: path.join(dir, '.cache') };
|
|
100
|
+
if (process.platform === 'win32') env.SystemRoot = process.env.SystemRoot;
|
|
101
|
+
return env;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function installRelease(home, input, options = {}) {
|
|
105
|
+
const localTestRegistry = /^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(options.registry ?? '');
|
|
106
|
+
const release = validRelease(input, { allowLocalTarball: localTestRegistry }), versions = path.join(home, 'versions'), destination = packageAt(home, release.version);
|
|
107
|
+
fs.mkdirSync(versions, { recursive: true, mode: 0o700 });
|
|
108
|
+
const marker = path.join(path.dirname(path.dirname(path.dirname(destination))), '.dalan-release.json');
|
|
109
|
+
if (fs.existsSync(destination)) {
|
|
110
|
+
let existing;
|
|
111
|
+
try { existing = JSON.parse(fs.readFileSync(marker, 'utf8')); } catch { fail(`installed version ${release.version} has no valid integrity receipt`); }
|
|
112
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(destination, 'package.json'), 'utf8'));
|
|
113
|
+
if (existing.integrity !== release.dist.integrity || pkg.name !== PACKAGE || pkg.version !== release.version) fail(`installed version ${release.version} does not match registry integrity`);
|
|
114
|
+
return destination;
|
|
115
|
+
}
|
|
116
|
+
const staging = path.join(versions, `.stage-${release.version}-${process.pid}-${randomBytes(5).toString('hex')}`);
|
|
117
|
+
fs.mkdirSync(staging, { recursive: true, mode: 0o700 });
|
|
118
|
+
const registry = options.registry ?? PUBLIC_REGISTRY;
|
|
119
|
+
if (!/^https:\/\//.test(registry) && !/^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(registry)) fail('npm registry must use HTTPS');
|
|
120
|
+
try {
|
|
121
|
+
const tarballName = `dalan-${release.version}.tgz`;
|
|
122
|
+
fs.writeFileSync(path.join(staging, tarballName), await fetchTarball(release.dist.tarball, release.dist.integrity, { timeout: options.timeout, fetchImpl: options.fetch }), { mode: 0o600 });
|
|
123
|
+
const pkg = { private: true, name: 'dalan-release-stage', version: '1.0.0', dependencies: { [PACKAGE]: `file:./${tarballName}` } };
|
|
124
|
+
fs.writeFileSync(path.join(staging, 'package.json'), JSON.stringify(pkg), { mode: 0o600 });
|
|
125
|
+
const env = installEnv(staging), npm = options.npm ?? 'npm';
|
|
126
|
+
const base = ['--ignore-scripts', '--no-audit', '--no-fund', '--registry', registry];
|
|
127
|
+
await (options.run ?? run)(npm, ['install', '--package-lock-only', ...base], { cwd: staging, env, timeout: options.timeout ?? TIMEOUT });
|
|
128
|
+
const lock = JSON.parse(fs.readFileSync(path.join(staging, 'package-lock.json'), 'utf8'));
|
|
129
|
+
if (lock.packages?.[`node_modules/${PACKAGE}`]?.integrity !== release.dist.integrity) fail('npm lock integrity does not match registry metadata');
|
|
130
|
+
await (options.run ?? run)(npm, ['ci', ...base, '--omit=dev'], { cwd: staging, env, timeout: options.timeout ?? TIMEOUT });
|
|
131
|
+
const installed = JSON.parse(fs.readFileSync(path.join(staging, 'node_modules', PACKAGE, 'package.json'), 'utf8'));
|
|
132
|
+
if (installed.name !== PACKAGE || installed.version !== release.version) fail('installed package identity does not match registry metadata');
|
|
133
|
+
fs.writeFileSync(path.join(staging, '.dalan-release.json'), JSON.stringify({ name: PACKAGE, version: release.version, integrity: release.dist.integrity }), { mode: 0o600 });
|
|
134
|
+
fs.rmSync(path.join(staging, '.cache'), { recursive: true, force: true });
|
|
135
|
+
fs.rmSync(path.join(staging, '.npmrc'), { force: true });
|
|
136
|
+
fs.rmSync(path.join(staging, tarballName), { force: true });
|
|
137
|
+
fs.renameSync(staging, path.join(versions, release.version));
|
|
138
|
+
return destination;
|
|
139
|
+
} catch (error) { fs.rmSync(staging, { recursive: true, force: true }); throw error; }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function validateProbe(value, { expectedWorkers, expectedVersion } = {}) {
|
|
143
|
+
if (!value || typeof value !== 'object' || typeof value.version !== 'string' || value.update_protocol !== 1 || !Number.isInteger(value.port) || value.port < 1 || value.port > 65535 || value.self_check !== true ||
|
|
144
|
+
!value.catalogs || typeof value.catalogs !== 'object' || Array.isArray(value.catalogs) || !Object.keys(value.catalogs).length) fail('service self-check response is incomplete');
|
|
145
|
+
for (const [worker, tools] of Object.entries(value.catalogs)) {
|
|
146
|
+
const names = new Set();
|
|
147
|
+
if (!/^[a-z][a-z0-9_-]{0,31}$/.test(worker) || !Array.isArray(tools) || !tools.length || tools.some(tool => {
|
|
148
|
+
if (!tool || typeof tool.name !== 'string' || !tool.name || names.has(tool.name) || typeof tool.description !== 'string' || !tool.inputSchema || typeof tool.inputSchema !== 'object') return true;
|
|
149
|
+
names.add(tool.name); return false;
|
|
150
|
+
})) fail('service self-check returned an invalid worker catalog');
|
|
151
|
+
}
|
|
152
|
+
if (expectedWorkers && JSON.stringify(Object.keys(value.catalogs).sort()) !== JSON.stringify([...expectedWorkers].sort())) fail('service self-check worker set does not match configuration');
|
|
153
|
+
if (expectedVersion && value.version !== expectedVersion) fail('service self-check version does not match selected package');
|
|
154
|
+
return value;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function expectedProbe(home, receipt, repo) {
|
|
158
|
+
const workers = JSON.parse(fs.readFileSync(defaultPath(home, '.config/dot-bridge', 'workers.json'), 'utf8'))?.workers;
|
|
159
|
+
if (!workers || typeof workers !== 'object' || Array.isArray(workers)) fail('worker configuration is invalid for service self-check');
|
|
160
|
+
const packageDir = repo ?? receipt?.repo ?? path.join(home, 'current');
|
|
161
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
|
|
162
|
+
return { expectedWorkers: Object.keys(workers), expectedVersion: manifest.version };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function probeService(home, _receipt, options = {}) {
|
|
166
|
+
const socketPath = defaultPath(home, '.local/share/dot-bridge', 'admin.sock');
|
|
167
|
+
const operator = fs.readFileSync(defaultPath(home, '.config/dot-bridge', 'operator.key'), 'utf8').trim();
|
|
168
|
+
if (!operator || operator.length > 1024) fail('service operator key is invalid');
|
|
169
|
+
const timeout = options.timeout ?? TIMEOUT;
|
|
170
|
+
if (!Number.isFinite(timeout) || timeout <= 0) fail('service probe timeout must be positive');
|
|
171
|
+
const deadline = performance.now() + timeout;
|
|
172
|
+
const expected = expectedProbe(home, _receipt);
|
|
173
|
+
let value;
|
|
174
|
+
try { value = validateProbe(await requestJson('http://localhost/service-check', { socketPath, headers: { 'x-operator-key': operator }, timeout }), expected); }
|
|
175
|
+
catch (error) {
|
|
176
|
+
// A 0.6.0 or 0.6.1 server answers on its admin socket but has no /service-check. That is a running legacy server with no update gate:
|
|
177
|
+
// the updater stops it, switches the package and starts it again. Its catalogs are unknown, so none are compared.
|
|
178
|
+
if (error.statusCode !== 404 || !_receipt?.port) throw error;
|
|
179
|
+
const left = deadline - performance.now();
|
|
180
|
+
if (left <= 0) fail('service probe timed out');
|
|
181
|
+
await checkLoopback(_receipt.port, left);
|
|
182
|
+
return { legacy: true, version: expected.expectedVersion, update_protocol: 0, port: _receipt.port, self_check: false, catalogs: null };
|
|
183
|
+
}
|
|
184
|
+
const remaining = deadline - performance.now();
|
|
185
|
+
if (remaining <= 0) fail('service probe timed out');
|
|
186
|
+
await checkLoopback(value.port, remaining);
|
|
187
|
+
return value;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function checkLoopback(port, timeout = 1500) {
|
|
191
|
+
return new Promise((resolve, reject) => {
|
|
192
|
+
const socket = net.connect({ host: '127.0.0.1', port });
|
|
193
|
+
const timer = setTimeout(() => socket.destroy(new Error('service listener check timed out')), timeout);
|
|
194
|
+
socket.once('connect', () => { clearTimeout(timer); socket.end(); resolve(); });
|
|
195
|
+
socket.once('error', error => { clearTimeout(timer); reject(new Error(`reported loopback listener is unavailable: ${error.message}`)); });
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// The candidate runs before promotion and may be incompatible or hostile. It receives configuration shape (workers, public origin)
|
|
200
|
+
// but never a live secret: signing keys, cookie keys, the storage key and the operator key are generated fresh for each probe.
|
|
201
|
+
function prepareProbeConfig(from, to) {
|
|
202
|
+
const source = defaultPath(from, '.config/dot-bridge'), target = defaultPath(to, '.config/dot-bridge');
|
|
203
|
+
fs.mkdirSync(target, { recursive: true, mode: 0o700 });
|
|
204
|
+
for (const name of ['workers.json', 'workers-repos.json']) {
|
|
205
|
+
const a = path.join(source, name); if (!fs.existsSync(a)) continue;
|
|
206
|
+
const stat = fs.lstatSync(a); if (!stat.isFile() || stat.isSymbolicLink()) continue;
|
|
207
|
+
fs.copyFileSync(a, path.join(target, name), fs.constants.COPYFILE_EXCL); fs.chmodSync(path.join(target, name), stat.mode & 0o777);
|
|
208
|
+
}
|
|
209
|
+
const origin = JSON.parse(fs.readFileSync(path.join(source, 'as.json'), 'utf8'));
|
|
210
|
+
initAsFiles(target, { publicUrl: origin.public_url });
|
|
211
|
+
fs.writeFileSync(path.join(target, 'as.json'), JSON.stringify({ ...origin, public_url: origin.public_url }), { mode: 0o600 });
|
|
212
|
+
fs.writeFileSync(path.join(target, 'operator.key'), `${randomBytes(32).toString('hex')}\n`, { mode: 0o600 });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function stopChild(child) {
|
|
216
|
+
if (!child || child.exitCode !== null || child.signalCode !== null || child.spawned === false) return;
|
|
217
|
+
if (!child.pid) return;
|
|
218
|
+
child.kill('SIGTERM');
|
|
219
|
+
let timer;
|
|
220
|
+
await Promise.race([new Promise(resolve => child.once('close', resolve)), new Promise(resolve => { timer = setTimeout(resolve, 3000); })]);
|
|
221
|
+
clearTimeout(timer);
|
|
222
|
+
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
|
223
|
+
if (child.exitCode === null && child.signalCode === null && child.spawned !== false) await new Promise(resolve => child.once('close', resolve));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function requireCatalogGuard(repo, env, receipt, options) {
|
|
227
|
+
const child = (options.spawn ?? spawn)(receipt.node ?? process.execPath, [path.join(repo, 'src/server.mjs')], { cwd: repo, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
228
|
+
let stdout = '', stderr = '';
|
|
229
|
+
let spawnError = null, closed = false;
|
|
230
|
+
child.on('error', error => { spawnError = error; });
|
|
231
|
+
child.once('close', () => { closed = true; });
|
|
232
|
+
child.stdout?.on('data', chunk => { if (stdout.length < 8192) stdout += chunk.toString().slice(0, 8192 - stdout.length); });
|
|
233
|
+
child.stderr?.on('data', chunk => { if (stderr.length < 8192) stderr += chunk.toString().slice(0, 8192 - stderr.length); });
|
|
234
|
+
try {
|
|
235
|
+
const deadline = Date.now() + (options.guardTimeoutMs ?? 10_000);
|
|
236
|
+
while (Date.now() < deadline) {
|
|
237
|
+
if (spawnError) fail(`candidate service could not start: ${spawnError.message}`);
|
|
238
|
+
if (/MCP listening|admin socket/.test(stdout)) fail('candidate started despite mismatched service catalog pin');
|
|
239
|
+
if (closed) break;
|
|
240
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
241
|
+
}
|
|
242
|
+
if (!closed) fail('candidate did not enforce the service catalog pin before timeout');
|
|
243
|
+
if (/MCP listening|admin socket/.test(stdout)) fail('candidate announced a listener before enforcing the service catalog pin');
|
|
244
|
+
if (child.exitCode === 0 || !stderr.includes('service catalog guard mismatch')) fail('candidate did not reject the mismatched service catalog pin');
|
|
245
|
+
} finally { await stopChild(child); }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export async function probeCandidate(home, receipt, repo, options = {}) {
|
|
249
|
+
const scratchBase = path.join(os.homedir(), '.tmp');
|
|
250
|
+
fs.mkdirSync(scratchBase, { recursive: true, mode: 0o700 });
|
|
251
|
+
const scratch = fs.mkdtempSync(path.join(scratchBase, 'dalan-candidate-'));
|
|
252
|
+
fs.chmodSync(scratch, 0o700);
|
|
253
|
+
let child;
|
|
254
|
+
try {
|
|
255
|
+
prepareProbeConfig(home, scratch);
|
|
256
|
+
const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: scratch, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', DALAN_BIND_HOST: '127.0.0.1', DALAN_PORT: '0', DALAN_CATALOG_PROFILE: 'stable', DALAN_ENABLE_WORKSPACE: receipt.enable_workspace ? '1' : '0', DALAN_ENABLE_T3_TOOLS: receipt.enable_t3 ? '1' : '0' };
|
|
257
|
+
const configDir = defaultPath(scratch, '.config/dot-bridge');
|
|
258
|
+
const pinFile = path.join(configDir, 'service-catalog.json');
|
|
259
|
+
const version = JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version;
|
|
260
|
+
fs.writeFileSync(pinFile, JSON.stringify({ version, catalogs: {} }), { mode: 0o600, flag: 'wx' });
|
|
261
|
+
try { await requireCatalogGuard(repo, env, receipt, options); }
|
|
262
|
+
finally { fs.rmSync(pinFile, { force: true }); }
|
|
263
|
+
child = (options.spawn ?? spawn)(receipt.node ?? process.execPath, [path.join(repo, 'src/server.mjs')], { cwd: repo, env, stdio: ['ignore', 'ignore', 'ignore'] });
|
|
264
|
+
let spawnError = null, closed = false;
|
|
265
|
+
child.on('error', error => { spawnError = error; });
|
|
266
|
+
child.once('close', () => { closed = true; });
|
|
267
|
+
const deadline = Date.now() + (options.startupTimeoutMs ?? 20_000);
|
|
268
|
+
let result;
|
|
269
|
+
while (Date.now() < deadline) {
|
|
270
|
+
if (spawnError) fail(`candidate service could not start: ${spawnError.message}`);
|
|
271
|
+
if (closed) fail('candidate service exited before self-check');
|
|
272
|
+
if (child.exitCode !== null || child.signalCode !== null) fail('candidate service exited before self-check');
|
|
273
|
+
try { result = await probeService(scratch, { ...receipt, repo }); break; } catch { await new Promise(resolve => setTimeout(resolve, 150)); }
|
|
274
|
+
}
|
|
275
|
+
if (!result) fail('candidate service did not pass its self-check before timeout');
|
|
276
|
+
return result;
|
|
277
|
+
} finally {
|
|
278
|
+
await stopChild(child);
|
|
279
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export async function controlService(receipt, action, options = {}) {
|
|
284
|
+
if (!['stop', 'restart', 'daemon-reload'].includes(action)) fail('unsupported service action');
|
|
285
|
+
const unit = String(receipt.unit ?? '');
|
|
286
|
+
if (!/^[A-Za-z0-9_.@-]+$/.test(unit)) fail('invalid service unit name');
|
|
287
|
+
if (receipt.platform === 'darwin') { (options.launchd ?? controlLaunchd)(receipt, action, options.launchdSeams); return; }
|
|
288
|
+
const name = unit.endsWith('.service') ? unit : `${unit}.service`;
|
|
289
|
+
await (options.run ?? run)('systemctl', ['--user', action, ...(action === 'daemon-reload' ? [] : [name])], { timeout: TIMEOUT });
|
|
290
|
+
}
|