ssh-net 26.11.3 → 26.11.66

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.
@@ -8,7 +8,10 @@
8
8
  // - **跳过 Match 块**(同理,Match 是条件覆盖,不是静态主机定义)
9
9
  // - 只收录精确别名(无通配的 Host 模式);`Host *` / `Host n*` 不入表
10
10
  // - 关键字大小写不敏感(ssh 规则),同块内同关键字取首次(ssh 首次生效)
11
- // - 行首 `#` 注释、空行忽略;不处理行尾注释(ssh 不支持行尾注释)
11
+ // - 行首 `#` 注释、空行忽略
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { SSH_NET_DIR_REL } from './constants.mjs';
12
15
 
13
16
  /**
14
17
  * @typedef {Object} StaticHost
@@ -16,23 +19,98 @@
16
19
  */
17
20
 
18
21
  const GLOB_CHARS = new Set(['*', '?', '!']);
22
+ const ROUTES_INCLUDE = `~/${SSH_NET_DIR_REL}/conf.d/*`;
19
23
 
20
24
  /** @param {string} pattern Host 模式 */
21
25
  function isExactPattern(pattern) {
22
26
  return ![...pattern].some((c) => GLOB_CHARS.has(c));
23
27
  }
24
28
 
29
+ /** 比较 Include 目录的真实位置。首次安装允许末尾目录还没创建,但不能跨过不存在的目录解析 .. */
30
+ function directoryLocation(dir) {
31
+ try { return fs.realpathSync.native(dir); } catch (err) {
32
+ if (['ENOTDIR', 'EACCES', 'EPERM', 'ELOOP'].includes(err.code)) return null;
33
+ if (err.code !== 'ENOENT') throw err;
34
+ const name = path.basename(dir);
35
+ if (name === '..' || fs.lstatSync(dir, { throwIfNoEntry: false })) return null;
36
+ const parent = directoryLocation(path.dirname(dir));
37
+ return parent && path.join(parent, name);
38
+ }
39
+ }
40
+
41
+ /** OpenSSH 9.9 起在 Include 中展开环境变量。只在用户实际使用该写法时查询版本 */
42
+ export function supportsIncludeEnv(runner) {
43
+ const r = runner.run('ssh', ['-V']);
44
+ const version = `${r.stderr} ${r.stdout}`.match(/\bOpenSSH_(\d+)\.(\d+)/);
45
+ if (r.code !== 0 || !version) throw new Error('无法确认 SSH 客户端版本,请使用 Include ~/.ssh/ssh-net/conf.d/*');
46
+ return Number(version[1]) > 9 || (Number(version[1]) === 9 && Number(version[2]) >= 9);
47
+ }
48
+
49
+ /** 用户配置的相对 Include 从 ~/.ssh 起算;只核对路径,不读片段内容 */
50
+ function includesRoutes(tokens, { sshDir, confDir }, allowEnv) {
51
+ return tokens.some((token) => {
52
+ // glob 末尾的 / 只选目录。遇到 .. 要按实际目录解析,不能跨过不存在的目录或软链
53
+ if (!token.endsWith('/*') || (token.startsWith('${HOME}/') && !allowEnv())) return false;
54
+ const expanded = token.replace(/^(?:~|\$\{HOME\})(?=\/)/, () => path.dirname(sshDir));
55
+ const dir = path.dirname(path.isAbsolute(expanded) ? expanded : `${sshDir}/${expanded}`);
56
+ if (!dir.split('/').includes('..') && path.normalize(dir) === confDir) return true;
57
+ const actual = directoryLocation(dir);
58
+ return actual !== null && actual === directoryLocation(confDir);
59
+ });
60
+ }
61
+
62
+ /** OpenSSH 参数可拼接引号内外的字串,# 只在参数开头引出注释 */
63
+ function configArgs(value) {
64
+ const words = [];
65
+ let word = '', quote = '', started = false;
66
+ for (let i = 0; i < value.length; i++) {
67
+ const c = value[i];
68
+ const next = value[i + 1];
69
+ if (c === '\\' && (['\\', '"', "'"].includes(next) || (!quote && (next === ' ' || next === '\t')))) {
70
+ word += value[++i];
71
+ } else if (quote) {
72
+ if (c === quote) quote = '';
73
+ else word += c;
74
+ } else if (c === '"' || c === "'") {
75
+ quote = c;
76
+ } else if (/\s/.test(c)) {
77
+ if (started) words.push(word);
78
+ word = ''; started = false;
79
+ continue;
80
+ } else if (c === '#' && !started) {
81
+ break;
82
+ } else {
83
+ word += c;
84
+ }
85
+ started = true;
86
+ }
87
+ if (quote) throw new Error('~/.ssh/config 中的引号没有闭合');
88
+ if (started) words.push(word);
89
+ return words;
90
+ }
91
+
92
+ function exactHosts(tokens) {
93
+ const excluded = tokens.filter((token) => token.startsWith('!')).map((token) => {
94
+ const pattern = token.slice(1).split(/([*?])/).map((part) =>
95
+ part === '*' ? '.*' : part === '?' ? '.' : RegExp.escape(part)).join('');
96
+ return new RegExp(`^${pattern}$`);
97
+ });
98
+ return tokens.filter((token) => isExactPattern(token) && !excluded.some((re) => re.test(token)));
99
+ }
100
+
25
101
  /**
26
102
  * 解析主 ssh config 的静态 Host 块。
27
103
  * @param {string} text ~/.ssh/config 原文
104
+ * @param {{sshDir:string, confDir:string}} [paths] 读取本机配置时核对顶部 Include
105
+ * @param {() => boolean} [allowEnv] 本机 SSH 是否能展开 Include 中的环境变量
28
106
  * @returns {Map<string, StaticHost>} key=精确别名
29
107
  */
30
- export function parseStaticHosts(text) {
108
+ export function parseStaticHosts(text, paths, allowEnv = () => false) {
31
109
  /** @type {Map<string, StaticHost>} */
32
110
  const table = new Map();
33
- /** @type {string[]} */
34
- let currentPatterns = [];
35
- let inMatch = false;
111
+ /** @type {string[]|null} 首个 Host/Match 前的 Include 对所有主机生效 */
112
+ let currentPatterns = null;
113
+ let routesIncluded = false;
36
114
 
37
115
  for (const raw of text.split('\n')) {
38
116
  const line = raw.trim();
@@ -41,33 +119,36 @@ export function parseStaticHosts(text) {
41
119
  const parsed = line.match(/^([^\s=]+)\s*(?:=\s*|\s+)(.*)$/);
42
120
  if (!parsed) continue;
43
121
  const keyword = parsed[1].toLowerCase();
44
- const cols = parsed[2] ? parsed[2].split(/\s+/) : [];
122
+ const value = parsed[2];
45
123
 
124
+ if (keyword === 'include') {
125
+ if (paths && currentPatterns === null) routesIncluded ||= includesRoutes(configArgs(value), paths, allowEnv);
126
+ continue;
127
+ }
46
128
  if (keyword === 'match') {
47
- inMatch = true;
48
129
  currentPatterns = [];
49
130
  continue;
50
131
  }
51
132
  if (keyword === 'host') {
52
- inMatch = false;
53
133
  // 精确模式入表(多模式逐个);同一别名多个 Host 块时 ssh 取首次值——
54
134
  // 已存在的记录对象继续沿用,首次值写入不被后块覆盖
55
- currentPatterns = cols.filter(isExactPattern);
135
+ currentPatterns = exactHosts(configArgs(value));
56
136
  for (const p of currentPatterns) {
57
137
  if (!table.has(p)) table.set(p, {});
58
138
  }
59
139
  continue;
60
140
  }
61
- if (inMatch || currentPatterns.length === 0) continue;
62
- if (keyword === 'hostname') {
63
- const value = cols.join(' ');
64
- if (value) {
65
- for (const p of currentPatterns) {
66
- const host = table.get(p);
67
- if (host.hostname === undefined) host.hostname = value;
68
- }
141
+ if (keyword === 'hostname' && currentPatterns?.length && value) {
142
+ const args = configArgs(value);
143
+ if (args.length !== 1 || !args[0]) throw new Error('~/.ssh/config 的 HostName 需要一个地址');
144
+ const [hostname] = args;
145
+ for (const p of currentPatterns) {
146
+ const host = table.get(p);
147
+ host.hostname ??= hostname;
69
148
  }
70
149
  }
71
150
  }
151
+ if (paths && !routesIncluded)
152
+ throw new Error(`~/.ssh/config 需要在首个 Host 或 Match 之前写入 Include ${ROUTES_INCLUDE}——请运行 dot apply ssh`);
72
153
  return table;
73
154
  }
@@ -4,10 +4,10 @@
4
4
  import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
- import { readDirOrEmpty, readFileOrNull, writeFileAtomic } from './fsutil.mjs';
7
+ import { readDirOrEmpty, readFileOrNull, removeObsoleteNames, writeFileAtomic } from './fsutil.mjs';
8
8
 
9
9
  /** @param {import('./exec.mjs').Runner} runner @param {string} unit 含 .service */
10
- const sc = (runner, args) => runner.run('systemctl', args);
10
+ const sc = (runner, args) => runner.run('systemctl', args, { env: { LC_ALL: 'C' } });
11
11
 
12
12
  /** 所有 reload 路径都把真失败抛出;恢复路径可给错误加「恢复后」前缀。 */
13
13
  export function daemonReload(runner, errorPrefix = '') {
@@ -16,7 +16,13 @@ export function daemonReload(runner, errorPrefix = '') {
16
16
  throw new Error(`${errorPrefix}systemctl daemon-reload 失败:${r.stderr.trim()}`);
17
17
  }
18
18
  export const enableUnit = (runner, unit) => sc(runner, ['enable', unit]);
19
- const disableUnit = (runner, unit) => sc(runner, ['disable', unit]);
19
+ function disableUnit(runner, unit, runtime = false) {
20
+ const r = sc(runner, runtime ? ['disable', '--runtime', unit] : ['disable', unit]);
21
+ const detail = r.stderr.trim();
22
+ if (r.code !== 0 && ![`Unit ${unit} not loaded.`, `Unit ${unit} does not exist.`, `Unit file ${unit} does not exist.`]
23
+ .some((message) => detail.endsWith(message)))
24
+ throw new Error(`systemctl disable 失败:${detail}`);
25
+ }
20
26
  export const startUnit = (runner, unit) => sc(runner, ['start', unit]);
21
27
  const stopUnit = (runner, unit) => sc(runner, ['stop', unit]);
22
28
  export const restartUnit = (runner, unit) => sc(runner, ['restart', unit]);
@@ -25,21 +31,13 @@ export const restartUnit = (runner, unit) => sc(runner, ['restart', unit]);
25
31
  * 磁盘上指定前缀的 unit 文件名(卸载清理改名前的残留;目录不存在时空)。
26
32
  * @param {string} unitDir
27
33
  * @param {string} prefix
34
+ * @param {boolean} [includePending] 停止和卸载时也处理仅剩更新记录的服务
28
35
  * @returns {string[]}
29
36
  */
30
- export function unitNamesOnDisk(unitDir, prefix) {
31
- return readDirOrEmpty(unitDir)
32
- .filter((f) => f.startsWith(prefix) && f.endsWith('.service'));
33
- }
34
-
35
- /** 没装/已卸的 unit 放行(stop 的 not-loaded 与 disable 的 does not exist
36
- * 两种真机文案都认),其余失败抛出——stop/uninstall 对不存在的 unit 幂等,
37
- * 但真失败不能谎报成功。start 不经这里:unit 缺失是「先 install」
38
- * 的真错误,与 mac 侧 startCore 查 plist 同口径 */
39
- export function disableIfInstalled(runner, unit) {
40
- const r = disableUnit(runner, unit);
41
- if (r.code !== 0 && !/(not loaded|does not exist)/.test(r.stderr))
42
- throw new Error(`systemctl disable 失败:${r.stderr.trim()}`);
37
+ export function unitNamesOnDisk(unitDir, prefix, includePending = false) {
38
+ const files = readDirOrEmpty(unitDir);
39
+ const names = includePending ? files.map(f => f.replace(/\.service\.pending$/, '.service')) : files;
40
+ return [...new Set(names.filter(f => f.startsWith(prefix) && f.endsWith('.service')))];
43
41
  }
44
42
 
45
43
  /**
@@ -51,40 +49,45 @@ export function disableIfInstalled(runner, unit) {
51
49
  * @param {string} unit
52
50
  */
53
51
  export function enableStart(runner, unit) {
54
- const e = enableUnit(runner, unit);
55
- if (e.code !== 0) throw new Error(`systemctl enable 失败:${e.stderr.trim()}`);
52
+ ensureEnabled(runner, unit);
56
53
  const r = startUnit(runner, unit);
57
54
  if (r.code !== 0) throw new Error(`systemctl start 失败:${r.stderr.trim()}`);
58
55
  }
59
56
 
60
- /** enable 先行再 restart(同 enableStart 的理由:先清 stop 残留的 disable)。 */
61
- export function enableRestart(runner, unit) {
57
+ function ensureEnabled(runner, unit) {
62
58
  const e = enableUnit(runner, unit);
63
59
  if (e.code !== 0) throw new Error(`systemctl enable 失败:${e.stderr.trim()}`);
60
+ }
61
+
62
+ function restart(runner, unit) {
64
63
  const r = restartUnit(runner, unit);
65
64
  if (r.code !== 0) throw new Error(`systemctl restart 失败:${r.stderr.trim()}`);
66
65
  }
67
66
 
68
67
  /** @returns {string} active|inactive|failed|... */
69
- export const isActive = (runner, unit) =>
70
- sc(runner, ['is-active', unit]).stdout.trim();
68
+ export function isActive(runner, unit) {
69
+ const r = sc(runner, ['is-active', unit]);
70
+ const state = r.stdout.trim();
71
+ // inactive/failed 也有非零退出码;此时 stdout 仍有状态,与无法连接 manager 区分
72
+ if (!state || ![0, 3, 4].includes(r.code))
73
+ throw new Error(`systemctl is-active 失败(${unit}):${r.stderr.trim() || r.error?.message || `exit ${r.code}`}`);
74
+ return state;
75
+ }
71
76
 
72
77
  /**
73
78
  * unit 内容校验:写进私有临时目录、**文件名与正式 unit 相同**(verify 要求
74
79
  * .service 后缀,basename 参与模板/实例语义),过了才允许落 /etc——坏 unit
75
80
  * 绝不进系统目录(否则下次 daemon-reload 就生效)。systemd-analyze 不存在
76
81
  * (ENOENT)视为通过:lint 尽力而为,不该让装不了它的机器无法安装。
77
- * @returns {{ok:boolean, stderr:string}}
78
82
  */
79
- function verifyUnitContent(runner, unitName, content) {
83
+ function verifyUnitContent(runner, { unitPath, unitName, content }) {
80
84
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ssh-net-unit-'));
81
85
  try {
82
86
  const file = path.join(dir, unitName);
83
87
  fs.writeFileSync(file, content, { mode: 0o644 });
84
88
  const r = runner.run('systemdAnalyze', ['verify', file]);
85
- if (r.error && r.error.code === 'ENOENT') return { ok: true, stderr: '' };
86
- // verify 对只告警也可能非零;这里把非零视为失败,命令层打印 stderr
87
- return { ok: r.code === 0, stderr: r.stderr };
89
+ if (r.code !== 0 && r.error?.code !== 'ENOENT')
90
+ throw new Error(`systemd-analyze verify 失败(未写入 ${unitPath}):\n${r.stderr}`);
88
91
  } finally {
89
92
  fs.rmSync(dir, { recursive: true, force: true });
90
93
  }
@@ -97,57 +100,213 @@ function verifyUnitContent(runner, unitName, content) {
97
100
  * @param {import('./exec.mjs').Runner} runner
98
101
  * @param {string} unit
99
102
  */
100
- export function stopIfLoaded(runner, unit) {
103
+ function stopIfLoaded(runner, unit) {
101
104
  const r = stopUnit(runner, unit);
102
- if (r.code !== 0 && !/not loaded/.test(r.stderr))
105
+ if (r.code !== 0 && !r.stderr.trim().endsWith(`Unit ${unit} not loaded.`))
103
106
  throw new Error(`systemctl stop 失败:${r.stderr.trim()}`);
104
107
  }
105
108
 
109
+ /** 停止并取消开机启动。已移除的 unit 无需再操作,其他失败照常报错 */
110
+ export function stopAndDisable(runner, unit) {
111
+ stopIfLoaded(runner, unit);
112
+ disableUnit(runner, unit);
113
+ disableUnit(runner, unit, true);
114
+ }
115
+
116
+ const pendingPath = unitPath => `${unitPath}.pending`;
117
+
118
+ export const hasPendingUpdate = unitPath => Boolean(fs.lstatSync(pendingPath(unitPath), { throwIfNoEntry: false }));
119
+
120
+ /** 人工停止也覆盖更新中断前保存的自启状态,以免下次安装失败又启动了旧服务 */
121
+ export function stopInstalledUnit(runner, unitDir, unit) {
122
+ stopAndDisable(runner, unit);
123
+ const file = pendingPath(path.join(unitDir, unit));
124
+ const saved = readFileOrNull(file);
125
+ if (saved !== null) {
126
+ const record = JSON.parse(saved);
127
+ record.state = { active: false, fileState: 'disabled', invocation: null };
128
+ writeFileAtomic(file, JSON.stringify(record), { mode: 0o600 });
129
+ }
130
+ }
131
+
132
+ /** 趁文件还在时停服并 disable,清掉开机启动的软链。调用方完成所有文件变更后再重载 */
133
+ export function removeUnits(runner, unitDir, units) {
134
+ for (const unit of units) {
135
+ stopAndDisable(runner, unit);
136
+ const unitPath = path.join(unitDir, unit);
137
+ fs.rmSync(pendingPath(unitPath), { force: true });
138
+ fs.rmSync(unitPath, { force: true });
139
+ }
140
+ }
141
+
142
+ function unitState(runner, unit, withInvocation = false) {
143
+ const props = ['-p', 'ActiveState', '-p', 'UnitFileState'];
144
+ if (withInvocation) props.push('-p', 'InvocationID');
145
+ const state = sc(runner, ['show', ...props, unit]);
146
+ if (state.code !== 0) throw new Error(`systemctl show 失败(${unit}):${state.stderr.trim()}`);
147
+ const activeState = state.stdout.match(/^ActiveState=(\S+)$/m)?.[1];
148
+ if (!activeState) throw new Error(`systemctl show 未返回 ${unit} 的运行状态`);
149
+ const fileState = state.stdout.match(/^UnitFileState=(\S+)$/m)?.[1];
150
+ if (!fileState) throw new Error(`systemctl show 未返回 ${unit} 的自启状态`);
151
+ const active = ['active', 'activating', 'reloading', 'refreshing'].includes(activeState);
152
+ const invocation = state.stdout.match(/^InvocationID=([0-9a-f]{32})$/m)?.[1];
153
+ if (withInvocation && active && (!invocation || /^0+$/.test(invocation)))
154
+ throw new Error(`systemctl show 未返回 ${unit} 的运行实例 ID`);
155
+ return { active, fileState, invocation: active ? invocation : null };
156
+ }
157
+
158
+ /** 各 unit 的运行和自启分别恢复,单步错误在尝试完其他服务后一起报告 */
159
+ function restoreUnits(runner, states, activeCommand = 'start') {
160
+ const failures = [];
161
+ for (const { unit, active, fileState } of states) {
162
+ const commands = [];
163
+ if (fileState === 'enabled') commands.push(['enable', unit]);
164
+ if (fileState === 'enabled-runtime') commands.push(['enable', '--runtime', unit]);
165
+ if (active) commands.push([activeCommand, unit]);
166
+ for (const args of commands) {
167
+ const r = sc(runner, args);
168
+ if (r.code !== 0) failures.push(new Error(`systemctl ${args.join(' ')} 失败:${r.stderr.trim()}`));
169
+ }
170
+ }
171
+ if (failures.length) throw new AggregateError(failures, failures.map(e => e.message).join(';'));
172
+ }
173
+
106
174
  /**
107
- * 对账一个 unit 到磁盘并确保服务在跑(与 mac 侧 syncPlist 同构,install 幂等
108
- * 不断连):字节相同只 enable+start,不重写不 restart;内容变了先在临时目录
109
- * verify → 通过才原子落盘 → daemon-reload → enable → restart;编排失败恢复
110
- * 旧文件与 manager,首装撤掉 enable/进程,更新用旧 unit 恢复启动。
175
+ * 确保服务在跑。新配置校验通过后先清除占用注册口的旧名字。同名更新只向
176
+ * systemd 提交完整的 restart;没有未完成的更新时,字节相同只 enable+start
111
177
  * @param {import('./exec.mjs').Runner} runner
112
178
  * @param {{unitPath:string, unitName:string, content:string}} job
179
+ * @param {string[]} [obsolete] 已改名的 unit,不含当前名字
113
180
  * @returns {{changed:boolean, restarted?:boolean}} 配置是否变化;restarted
114
181
  * 只在更新已存在的 unit 时为真,用于提示可能断连
115
182
  */
116
- export function syncUnit(runner, { unitPath, unitName, content }) {
117
- fs.mkdirSync(path.dirname(unitPath), { recursive: true });
118
-
183
+ export function syncUnit(runner, job, obsolete = []) {
184
+ const { unitPath, unitName, content } = job;
185
+ const unitDir = path.dirname(unitPath);
186
+ fs.mkdirSync(unitDir, { recursive: true });
119
187
  const previous = readFileOrNull(unitPath);
120
- if (previous === content) {
188
+ if (previous !== content) verifyUnitContent(runner, job);
189
+ if (!obsolete.length) return deployUnit(runner, job, previous);
190
+
191
+ // 同时记录运行与自启状态,回滚时才能保留人工停止或临时启用的服务
192
+ const stopped = [];
193
+ let result;
194
+ // 支持启用大小写折叠的 Linux 目录。旧文件能由新拼写读取,但 manager 仍按旧名字识别服务
195
+ const diskNames = previous !== null ? new Set(readDirOrEmpty(unitDir)) : new Set();
196
+ const oldSpelling = !diskNames.has(unitName) && obsolete.find(old => diskNames.has(old) && old.toLowerCase() === unitName.toLowerCase());
197
+ const existingTarget = previous === content && !oldSpelling ? unitState(runner, unitName) : null;
198
+ let deploying = false;
199
+ try {
200
+ for (const unit of obsolete) {
201
+ stopped.push({ unit, ...unitState(runner, unit) });
202
+ stopAndDisable(runner, unit);
203
+ }
204
+ deploying = true;
205
+ result = deployUnit(runner, job, oldSpelling ? null : previous, Boolean(oldSpelling));
206
+ } catch (err) {
207
+ const failures = [];
208
+ if (deploying && oldSpelling) {
209
+ try {
210
+ writeFileAtomic(path.join(unitDir, oldSpelling), previous, { mode: 0o644 });
211
+ daemonReload(runner, '恢复后 ');
212
+ } catch (restore) { failures.push(restore); }
213
+ }
214
+ if (deploying && existingTarget && existingTarget.fileState !== 'enabled') {
215
+ try { disableUnit(runner, unitName); } catch (restore) { failures.push(restore); }
216
+ }
217
+ try { restoreUnits(runner, stopped); } catch (restore) { failures.push(restore); }
218
+ if (failures.length)
219
+ throw new AggregateError([err, ...failures], `${err.message};恢复旧中继失败:${failures.map(e => e.message).join(';')}`);
220
+ throw err;
221
+ }
222
+ for (const old of obsolete) fs.rmSync(pendingPath(path.join(unitDir, old)), { force: true });
223
+ removeObsoleteNames(unitDir, obsolete, [unitName]);
224
+ daemonReload(runner);
225
+ return result;
226
+ }
227
+
228
+ function restoreDefinition(runner, unitName, state) {
229
+ daemonReload(runner, '恢复后 ');
230
+ if (state.fileState !== 'enabled') disableUnit(runner, unitName);
231
+ let command = 'start';
232
+ if (state.active) {
233
+ const current = unitState(runner, unitName, true);
234
+ if (current.active && current.invocation !== state.invocation) command = 'restart';
235
+ } else {
236
+ // 即使当前已在退出,也要取消 Restart=always 或排队中的启动任务
237
+ stopIfLoaded(runner, unitName);
238
+ }
239
+ restoreUnits(runner, [{ ...state, unit: unitName }], command);
240
+ }
241
+
242
+ function deployUnit(runner, { unitPath, unitName, content }, previous, renamed = false) {
243
+ const pending = pendingPath(unitPath);
244
+ let saved = renamed ? null : readFileOrNull(pending);
245
+ let resuming = saved !== null;
246
+ if (previous === content && !resuming) {
121
247
  enableStart(runner, unitName);
122
248
  return { changed: false };
123
249
  }
124
250
 
125
- const verify = verifyUnitContent(runner, unitName, content);
126
- if (!verify.ok)
127
- throw new Error(`systemd-analyze verify 失败(未写入 ${unitPath}):\n${verify.stderr}`);
128
- writeFileAtomic(unitPath, content, { mode: 0o644 });
251
+ let record = resuming ? JSON.parse(saved) : null;
252
+ if (record && record.target === previous && record.beforeRestart !== undefined) {
253
+ const current = unitState(runner, unitName, true);
254
+ if (current.active && current.invocation !== record.beforeRestart) {
255
+ // 上次的目标已在运行。继续安装其他配置时,失败应恢复到这个实例
256
+ if (previous === content) enableStart(runner, unitName);
257
+ fs.rmSync(pending, { force: true });
258
+ if (previous === content) return { changed: false };
259
+ record = null;
260
+ saved = null;
261
+ resuming = false;
262
+ }
263
+ }
264
+ if (!record && previous !== null) record = { previous, state: unitState(runner, unitName, true) };
265
+
266
+ // 省略编号表示尚未准备重启,null 表示重启前服务已停
267
+ function savePending(beforeRestart) {
268
+ const text = JSON.stringify({ ...record, target: content, beforeRestart });
269
+ if (saved === text) return;
270
+ writeFileAtomic(pending, text, { mode: 0o600 });
271
+ saved = text;
272
+ }
273
+
274
+ let restarted = false;
129
275
  try {
276
+ if (previous !== content) {
277
+ if (record) savePending(); // 远程会话可能断开,先留下旧定义和原自启状态
278
+ writeFileAtomic(unitPath, content, { mode: 0o644 });
279
+ }
130
280
  daemonReload(runner);
131
- enableRestart(runner, unitName);
281
+ ensureEnabled(runner, unitName);
282
+ // 只认加载新定义之后的实例变更,不能拿 daemon-reload 本身当作重启
283
+ const current = record ? unitState(runner, unitName, true) : null;
284
+ const originalRunning = current?.active && record.previous === content && current.invocation === record.state.invocation;
285
+ if (!originalRunning) {
286
+ if (record) savePending(current.invocation);
287
+ restart(runner, unitName);
288
+ restarted = previous !== null;
289
+ }
132
290
  } catch (err) {
133
- // 文件相同只能表示部署完成:失败时恢复旧文件并重载 manager;首装撤掉
134
- // enable/进程,更新用旧 unit 恢复启动,下一次 install 仍能重新对账。
135
291
  try {
136
- if (previous === null) {
137
- // disable 必须在删 unit 前:unit 缺失时 systemctl 会拒绝 disable,
138
- // 而幂等规则会放行 does not exist,遗留 wants 软链。
139
- stopIfLoaded(runner, unitName);
140
- disableIfInstalled(runner, unitName);
141
- fs.rmSync(unitPath);
142
- } else {
143
- writeFileAtomic(unitPath, previous, { mode: 0o644 });
292
+ if (record) {
293
+ const replaced = readFileOrNull(unitPath) !== record.previous;
294
+ if (replaced) {
295
+ // 回滚本身也可能中断;新定义的重启记录不能拿来确认旧定义
296
+ savePending();
297
+ writeFileAtomic(unitPath, record.previous, { mode: 0o644 });
298
+ }
299
+ if (replaced || resuming) restoreDefinition(runner, unitName, record.state);
300
+ fs.rmSync(pending, { force: true });
301
+ } else if (readFileOrNull(unitPath) !== null) {
302
+ removeUnits(runner, path.dirname(unitPath), [unitName]);
303
+ daemonReload(runner, '恢复后 ');
144
304
  }
145
- daemonReload(runner, '恢复后 ');
146
- if (previous !== null) enableRestart(runner, unitName);
147
305
  } catch (rollbackError) {
148
306
  throw new AggregateError([err, rollbackError], `${err.message};恢复 systemd 状态失败:${rollbackError.message}`);
149
307
  }
150
308
  throw err;
151
309
  }
152
- return { changed: true, restarted: previous !== null };
310
+ if (record) fs.rmSync(pending, { force: true });
311
+ return { changed: restarted || previous !== content, restarted };
153
312
  }
package/libexec/sn-ipv6 CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/bin/bash
2
2
  # sn-ipv6:选取本机可注册的公网 v6——默认路由网卡上 2000::/3 全局单播、
3
- # autoconf secured、非 deprecated/temporary 的第一个地址(design §6.4)。
3
+ # 选已就绪的 autoconf secured 地址,过滤临时、过期和重复地址(design §6.4)。
4
4
  # 无输出 = 没有可注册 v6(v4-only/咖啡厅场景),退出码恒 0。
5
5
  # SSH_NET_V6_ALLOW_ULA=1 额外收 fc00::/7 ULA——仅测试注入用的强制开关
6
6
  #(喂参测试模拟纯 ULA 网络),生产路径恒不设置、默认只认公网 2000::/3。
@@ -55,7 +55,7 @@ while IFS= read -r line; do
55
55
  [ "${1:-}" = "inet6" ] || continue
56
56
  # link-local 只有 secured 无 autoconf,故两标记必须同时在
57
57
  case "$line" in *autoconf*secured*) ;; *) continue ;; esac
58
- case "$line" in *deprecated*|*temporary*) continue ;; esac
58
+ case "$line" in *deprecated*|*temporary*|*tentative*|*duplicated*|*detached*) continue ;; esac
59
59
  addr=${2%%%*} # 去可能的 scope
60
60
  if in_allowed_range "$addr"; then
61
61
  printf '%s\n' "$addr"