odant-work 1.0.102 → 1.0.103

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.
@@ -0,0 +1,281 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Настройка автозапуска ODANT-WORK при перезагрузке ОС:
4
+ * - Windows: Планировщик заданий (`schtasks`, задача `ODANT-WORK` -> `scripts/watchdog.mjs --boot`,
5
+ * сначала при старте ОС под SYSTEM; если нет прав администратора — при входе пользователя).
6
+ * - Linux : `systemd` (`odant-work.service` с `Restart=on-failure`, системный юнит для root или `--user` для обычного пользователя);
7
+ * если `systemd` недоступен — `crontab @reboot` через `scripts/watchdog.mjs --boot`.
8
+ *
9
+ * Использование:
10
+ * node scripts/autostart.mjs [install|remove|status] [--root=...]
11
+ */
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import childProcess from 'node:child_process';
16
+ import { pathToFileURL } from 'node:url';
17
+ import { resolveEntryScript, resolveWorkRoot } from './watchdog.mjs';
18
+
19
+ const WIN_TASK_NAME = 'ODANT-WORK';
20
+ const LINUX_UNIT_NAME = 'odant-work.service';
21
+
22
+ function runCmd(cmd, args, opts = {}) {
23
+ return childProcess.spawnSync(cmd, args, {
24
+ encoding: 'utf8',
25
+ stdio: opts.stdio || ['ignore', 'pipe', 'pipe'],
26
+ windowsHide: true,
27
+ ...opts,
28
+ });
29
+ }
30
+
31
+ function buildWindowsTaskCommand(nodePath, watchdogPath, workRoot) {
32
+ return `"${nodePath}" "${watchdogPath}" --boot "--root=${workRoot}"`;
33
+ }
34
+
35
+ function configureWindowsTaskOptions() {
36
+ const ps = [
37
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command',
38
+ `$t = Get-ScheduledTask -TaskName '${WIN_TASK_NAME}' -ErrorAction SilentlyContinue; `
39
+ + `if ($t) { $s = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1); Set-ScheduledTask -TaskName '${WIN_TASK_NAME}' -Settings $s | Out-Null }`,
40
+ ];
41
+ runCmd('powershell', ps);
42
+ }
43
+
44
+ function installWindows(workRoot) {
45
+ const watchdogPath = path.resolve(import.meta.dirname, 'watchdog.mjs');
46
+ const tr = buildWindowsTaskCommand(process.execPath, watchdogPath, workRoot);
47
+
48
+ // 1. Попытка системной задачи при старте ОС (до входа пользователя)
49
+ let res = runCmd('schtasks', [
50
+ '/Create', '/TN', WIN_TASK_NAME,
51
+ '/TR', tr,
52
+ '/SC', 'ONSTART',
53
+ '/RU', 'SYSTEM',
54
+ '/RL', 'HIGHEST',
55
+ '/F',
56
+ ]);
57
+ if (res.status === 0) {
58
+ configureWindowsTaskOptions();
59
+ console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" установлена на старт ОС (SYSTEM, ONSTART).`);
60
+ return { ok: true, platform: 'win32', scope: 'system', trigger: 'ONSTART' };
61
+ }
62
+
63
+ // 2. Fallback без прав администратора — при входе текущего пользователя
64
+ res = runCmd('schtasks', [
65
+ '/Create', '/TN', WIN_TASK_NAME,
66
+ '/TR', tr,
67
+ '/SC', 'ONLOGON',
68
+ '/RL', 'LIMITED',
69
+ '/F',
70
+ ]);
71
+ if (res.status === 0) {
72
+ configureWindowsTaskOptions();
73
+ console.log(`[autostart] Windows: нет прав администратора для ONSTART — установлена задача "${WIN_TASK_NAME}" при входе пользователя (ONLOGON).`);
74
+ console.log('[autostart] Для запуска до входа пользователя выполните скрипт от имени администратора.');
75
+ return { ok: true, platform: 'win32', scope: 'user', trigger: 'ONLOGON' };
76
+ }
77
+
78
+ const errText = (res.stderr || res.stdout || '').trim() || `exit ${res.status}`;
79
+ throw new Error(`Не удалось создать задачу Планировщика Windows: ${errText}`);
80
+ }
81
+
82
+ function removeWindows() {
83
+ const res = runCmd('schtasks', ['/Delete', '/TN', WIN_TASK_NAME, '/F']);
84
+ if (res.status === 0) {
85
+ console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" удалена.`);
86
+ return { ok: true, removed: true };
87
+ }
88
+ const msg = (res.stderr || res.stdout || '').trim();
89
+ if (/cannot find|не удается найти/i.test(msg)) {
90
+ console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" не была установлена.`);
91
+ return { ok: true, removed: false };
92
+ }
93
+ throw new Error(`Ошибка удаления задачи "${WIN_TASK_NAME}": ${msg || res.status}`);
94
+ }
95
+
96
+ function statusWindows() {
97
+ const res = runCmd('schtasks', ['/Query', '/TN', WIN_TASK_NAME, '/FO', 'LIST', '/V']);
98
+ if (res.status === 0) {
99
+ console.log(`[autostart] Windows: задача "${WIN_TASK_NAME}" установлена.`);
100
+ const lines = String(res.stdout || '').split(/\r?\n/).filter(l => /TaskName|Статус|Status|Schedule Type|Тип расписания|Run As User|Запуск от имени|Task To Run|Выполнить/i.test(l));
101
+ for (const l of lines)
102
+ console.log(' ' + l.trim());
103
+ return { installed: true, platform: 'win32' };
104
+ }
105
+ console.log(`[autostart] Windows: автозапуск не настроен (задача "${WIN_TASK_NAME}" отсутствует).`);
106
+ return { installed: false, platform: 'win32' };
107
+ }
108
+
109
+ export function buildSystemdUnit({ nodePath, entryScript, workRoot, user = '' } = {}) {
110
+ const lines = [
111
+ '[Unit]',
112
+ 'Description=ODANT-WORK Platform Server',
113
+ 'After=network-online.target',
114
+ 'Wants=network-online.target',
115
+ '',
116
+ '[Service]',
117
+ 'Type=simple',
118
+ `WorkingDirectory=${workRoot}`,
119
+ `ExecStart="${nodePath}" "${entryScript}"`,
120
+ 'Restart=on-failure',
121
+ 'RestartSec=3',
122
+ 'Environment=WORK_NO_BROWSER=1',
123
+ 'KillSignal=SIGTERM',
124
+ 'TimeoutStopSec=15',
125
+ ];
126
+ if (user)
127
+ lines.push(`User=${user}`);
128
+ lines.push('', '[Install]', 'WantedBy=multi-user.target', '');
129
+ return lines.join('\n');
130
+ }
131
+
132
+ function hasSystemd() {
133
+ if (!fs.existsSync('/run/systemd/system'))
134
+ return false;
135
+ const r = runCmd('systemctl', ['--version']);
136
+ return r.status === 0;
137
+ }
138
+
139
+ function isRootLinux() {
140
+ return typeof process.getuid === 'function' && process.getuid() === 0;
141
+ }
142
+
143
+ function installLinuxCron(workRoot) {
144
+ const watchdogPath = path.resolve(import.meta.dirname, 'watchdog.mjs');
145
+ const marker = `# odant-work-autostart:${workRoot}`;
146
+ const cronLine = `@reboot "${process.execPath}" "${watchdogPath}" --boot "--root=${workRoot}" ${marker}`;
147
+ const cur = runCmd('crontab', ['-l']);
148
+ const existing = (cur.status === 0 ? cur.stdout : '')
149
+ .split(/\r?\n/)
150
+ .filter(l => l.trim() && !l.includes(marker));
151
+ existing.push(cronLine);
152
+ const put = childProcess.spawnSync('crontab', ['-'], {
153
+ input: existing.join('\n') + '\n',
154
+ encoding: 'utf8',
155
+ });
156
+ if (put.status !== 0)
157
+ throw new Error(`Не удалось обновить crontab: ${(put.stderr || put.stdout || '').trim()}`);
158
+ console.log(`[autostart] Linux (cron @reboot): добавлена запись автозапуска с watchdog для ${workRoot}.`);
159
+ return { ok: true, platform: 'linux', mode: 'cron' };
160
+ }
161
+
162
+ function installLinux(workRoot) {
163
+ const entryScript = resolveEntryScript(workRoot);
164
+ if (hasSystemd()) {
165
+ if (isRootLinux()) {
166
+ const unitPath = `/etc/systemd/system/${LINUX_UNIT_NAME}`;
167
+ fs.writeFileSync(unitPath, buildSystemdUnit({ nodePath: process.execPath, entryScript, workRoot }), 'utf8');
168
+ const r1 = runCmd('systemctl', ['daemon-reload']);
169
+ const r2 = runCmd('systemctl', ['enable', '--now', LINUX_UNIT_NAME]);
170
+ if (r1.status !== 0 || r2.status !== 0)
171
+ throw new Error(`Ошибка systemctl: ${(r2.stderr || r1.stderr || '').trim()}`);
172
+ console.log(`[autostart] Linux (systemd): установлен системный юнит ${unitPath} (Restart=on-failure).`);
173
+ return { ok: true, platform: 'linux', mode: 'systemd-system', unitPath };
174
+ }
175
+ const userDir = path.join(os.homedir(), '.config', 'systemd', 'user');
176
+ fs.mkdirSync(userDir, { recursive: true });
177
+ const unitPath = path.join(userDir, LINUX_UNIT_NAME);
178
+ const userUnit = buildSystemdUnit({ nodePath: process.execPath, entryScript, workRoot })
179
+ .replace('WantedBy=multi-user.target', 'WantedBy=default.target');
180
+ fs.writeFileSync(unitPath, userUnit, 'utf8');
181
+ runCmd('systemctl', ['--user', 'daemon-reload']);
182
+ const r = runCmd('systemctl', ['--user', 'enable', '--now', LINUX_UNIT_NAME]);
183
+ if (r.status === 0) {
184
+ const userName = os.userInfo().username;
185
+ runCmd('loginctl', ['enable-linger', userName]);
186
+ console.log(`[autostart] Linux (systemd --user): установлен пользовательский юнит ${unitPath}.`);
187
+ console.log('[autostart] Для системного юнита (до входа пользователя) запустите от root.');
188
+ return { ok: true, platform: 'linux', mode: 'systemd-user', unitPath };
189
+ }
190
+ }
191
+ return installLinuxCron(workRoot);
192
+ }
193
+
194
+ function removeLinux(workRoot) {
195
+ let removed = false;
196
+ if (hasSystemd()) {
197
+ if (isRootLinux() && fs.existsSync(`/etc/systemd/system/${LINUX_UNIT_NAME}`)) {
198
+ runCmd('systemctl', ['disable', '--now', LINUX_UNIT_NAME]);
199
+ fs.rmSync(`/etc/systemd/system/${LINUX_UNIT_NAME}`, { force: true });
200
+ runCmd('systemctl', ['daemon-reload']);
201
+ removed = true;
202
+ }
203
+ const userUnit = path.join(os.homedir(), '.config', 'systemd', 'user', LINUX_UNIT_NAME);
204
+ if (fs.existsSync(userUnit)) {
205
+ runCmd('systemctl', ['--user', 'disable', '--now', LINUX_UNIT_NAME]);
206
+ fs.rmSync(userUnit, { force: true });
207
+ runCmd('systemctl', ['--user', 'daemon-reload']);
208
+ removed = true;
209
+ }
210
+ }
211
+ const marker = `# odant-work-autostart:${workRoot}`;
212
+ const cur = runCmd('crontab', ['-l']);
213
+ if (cur.status === 0 && cur.stdout.includes(marker)) {
214
+ const filtered = cur.stdout.split(/\r?\n/).filter(l => l.trim() && !l.includes(marker));
215
+ childProcess.spawnSync('crontab', ['-'], { input: filtered.length ? filtered.join('\n') + '\n' : '', encoding: 'utf8' });
216
+ removed = true;
217
+ }
218
+ console.log(removed
219
+ ? '[autostart] Linux: автозапуск удалён.'
220
+ : '[autostart] Linux: автозапуск не был настроен.');
221
+ return { ok: true, removed };
222
+ }
223
+
224
+ function statusLinux(workRoot) {
225
+ if (hasSystemd()) {
226
+ if (fs.existsSync(`/etc/systemd/system/${LINUX_UNIT_NAME}`)) {
227
+ const st = runCmd('systemctl', ['is-enabled', LINUX_UNIT_NAME]);
228
+ const act = runCmd('systemctl', ['is-active', LINUX_UNIT_NAME]);
229
+ console.log(`[autostart] Linux (systemd system): enabled=${(st.stdout || '').trim()}, active=${(act.stdout || '').trim()}`);
230
+ return { installed: true, mode: 'systemd-system' };
231
+ }
232
+ const userUnit = path.join(os.homedir(), '.config', 'systemd', 'user', LINUX_UNIT_NAME);
233
+ if (fs.existsSync(userUnit)) {
234
+ const st = runCmd('systemctl', ['--user', 'is-enabled', LINUX_UNIT_NAME]);
235
+ const act = runCmd('systemctl', ['--user', 'is-active', LINUX_UNIT_NAME]);
236
+ console.log(`[autostart] Linux (systemd --user): enabled=${(st.stdout || '').trim()}, active=${(act.stdout || '').trim()}`);
237
+ return { installed: true, mode: 'systemd-user' };
238
+ }
239
+ }
240
+ const marker = `# odant-work-autostart:${workRoot}`;
241
+ const cur = runCmd('crontab', ['-l']);
242
+ if (cur.status === 0 && cur.stdout.includes(marker)) {
243
+ console.log('[autostart] Linux (cron @reboot): автозапуск настроен.');
244
+ return { installed: true, mode: 'cron' };
245
+ }
246
+ console.log('[autostart] Linux: автозапуск не настроен.');
247
+ return { installed: false };
248
+ }
249
+
250
+ export async function runAutostartCommand(action = 'status', { workRoot = resolveWorkRoot() } = {}) {
251
+ const act = String(action || 'status').toLowerCase();
252
+ if (process.platform === 'win32') {
253
+ if (act === 'install' || act === 'on' || act === 'enable')
254
+ return installWindows(workRoot);
255
+ if (act === 'remove' || act === 'uninstall' || act === 'off' || act === 'disable')
256
+ return removeWindows();
257
+ return statusWindows();
258
+ }
259
+ if (process.platform === 'linux') {
260
+ if (act === 'install' || act === 'on' || act === 'enable')
261
+ return installLinux(workRoot);
262
+ if (act === 'remove' || act === 'uninstall' || act === 'off' || act === 'disable')
263
+ return removeLinux(workRoot);
264
+ return statusLinux(workRoot);
265
+ }
266
+ throw new Error(`Автозапуск поддерживается на Windows и Linux (текущая ОС: ${process.platform})`);
267
+ }
268
+
269
+ const isMain = process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
270
+ if (isMain) {
271
+ const args = process.argv.slice(2);
272
+ const rootArg = args.find(a => a.startsWith('--root='))?.slice(7) || '';
273
+ const action = args.find(a => !a.startsWith('-')) || 'install';
274
+ try {
275
+ await runAutostartCommand(action, { workRoot: resolveWorkRoot(rootArg) });
276
+ }
277
+ catch (err) {
278
+ console.error('[autostart]', err?.message || err);
279
+ process.exit(1);
280
+ }
281
+ }