vcs-patch-deploy 1.2.0 → 1.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.
@@ -1,6 +1,20 @@
1
1
  <?php
2
2
  declare(strict_types=1);
3
3
 
4
+ // PHP 7.4 兼容:str_starts_with / str_ends_with 是 PHP 8.0 才内置的函数
5
+ if (!function_exists('str_starts_with')) {
6
+ function str_starts_with(string $haystack, string $needle): bool
7
+ {
8
+ return $needle === '' || strncmp($haystack, $needle, strlen($needle)) === 0;
9
+ }
10
+ }
11
+ if (!function_exists('str_ends_with')) {
12
+ function str_ends_with(string $haystack, string $needle): bool
13
+ {
14
+ return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
15
+ }
16
+ }
17
+
4
18
  /**
5
19
  * 堡垒机增量部署:将 patch 包内文件覆盖到线上 Backend 根目录,并清理 ThinkPHP 缓存。
6
20
  *
@@ -9,10 +23,16 @@ declare(strict_types=1);
9
23
  * 或设置环境变量:
10
24
  * PATCH_BACKEND_ROOT=/path/to/production-api php apply-update.php
11
25
  *
12
- * 安全:不会覆盖 .env;不会自动删除 MANIFEST-deleted.txt 中列出的文件。
26
+ * 安全:不会覆盖 .env(含 .env.*);不会自动删除 MANIFEST-deleted.txt 中列出的文件;
27
+ * 拒绝包内绝对路径、../ 逃逸路径与符号链接。
28
+ * 保护:包内 PROTECT.txt 列出的文件,线上已存在时跳过覆盖(不存在时仍写入)。
13
29
  * 备份:覆盖前将线上已有文件复制到版本备份目录(默认 Backend/.deploy-backups/v1.2.2/ 或 r467/)。
30
+ * 默认保留最近 10 个备份会话(--keep-backups=N / PATCH_KEEP_BACKUPS 调整)。
14
31
  * 回滚:php apply-update.php --rollback[=版本] <Backend根目录>
32
+ * 回滚会恢复被覆盖的旧文件(含权限),并删除本次部署新增且未被修改过的文件。
15
33
  * 列表:php apply-update.php --list-backups <Backend根目录>
34
+ *
35
+ * 要求 PHP >= 7.4。
16
36
  */
17
37
 
18
38
  /** patch 包根目录(本脚本所在目录) */
@@ -27,12 +47,17 @@ const DEPLOY_VERSION_FILE = '.deploy-version';
27
47
  /** 版本备份元数据文件名 */
28
48
  const DEPLOY_META_FILE = 'DEPLOY-META.txt';
29
49
 
50
+ /** 备份会话标记文件(用于清理失败/无元数据的旧会话) */
51
+ const BACKUP_SESSION_MARKER = '.deploy-backup-session';
52
+
30
53
  /** 部署时跳过的文件名(相对路径 basename 匹配或完整相对路径) */
31
54
  const SKIP_FILES = [
32
55
  'apply-update.php',
33
56
  'MANIFEST.txt',
34
57
  'MANIFEST-deleted.txt',
35
58
  'VERSION.txt',
59
+ 'PROTECT.txt',
60
+ 'MODES.txt',
36
61
  ];
37
62
 
38
63
  /** 永不覆盖的相对路径(保护生产配置与运行时数据) */
@@ -76,12 +101,15 @@ function resolveBackendRoot(): string
76
101
  if (str_starts_with($arg, '--rollback=')) {
77
102
  continue;
78
103
  }
104
+ if (str_starts_with($arg, '--keep-backups=')) {
105
+ continue;
106
+ }
79
107
  if ($arg !== '' && !str_starts_with($arg, '-')) {
80
108
  return rtrim($arg, "/\\");
81
109
  }
82
110
  }
83
111
 
84
- fwrite(STDERR, "用法: php apply-update.php [--check] [--rollback[=版本]] [--list-backups] [--files=<路径>] <Backend根目录>\n");
112
+ fwrite(STDERR, "用法: php apply-update.php [--check] [--rollback[=版本]] [--list-backups] [--keep-backups=N] [--files=<路径>] <Backend根目录>\n");
85
113
  fwrite(STDERR, "示例: php apply-update.php /path/to/production-api\n");
86
114
  fwrite(STDERR, " php apply-update.php --rollback /path/to/production-api\n");
87
115
  fwrite(STDERR, " php apply-update.php --rollback=1.2.2 /path/to/production-api\n");
@@ -126,6 +154,354 @@ function sanitizeVersionLabel(string $version): string
126
154
  return $label;
127
155
  }
128
156
 
157
+ /**
158
+ * 判断包内相对路径是否安全(拒绝绝对路径、盘符、.. 逃逸与空字节)
159
+ */
160
+ function isSafeRelativePath(string $rel): bool
161
+ {
162
+ if ($rel === '' || strpos($rel, "\0") !== false) {
163
+ return false;
164
+ }
165
+
166
+ $normalized = str_replace('\\', '/', $rel);
167
+ if (str_starts_with($normalized, '/') || preg_match('#^[A-Za-z]:/#', $normalized) === 1) {
168
+ return false;
169
+ }
170
+
171
+ foreach (explode('/', $normalized) as $segment) {
172
+ if ($segment === '..') {
173
+ return false;
174
+ }
175
+ }
176
+
177
+ return true;
178
+ }
179
+
180
+ /**
181
+ * 永不覆盖的生产配置(根目录与任意目录下的 .env / .env.*)
182
+ */
183
+ function isProtectedRelativePath(string $rel): bool
184
+ {
185
+ $normalized = str_replace('\\', '/', $rel);
186
+ if (in_array($normalized, PROTECTED_RELATIVE, true)) {
187
+ return true;
188
+ }
189
+
190
+ $base = basename($normalized);
191
+
192
+ return $base === '.env' || str_starts_with($base, '.env.');
193
+ }
194
+
195
+ /**
196
+ * 读取包内 PROTECT.txt(每行一个相对路径,# 为注释)
197
+ *
198
+ * 受保护语义:线上已存在则跳过覆盖;线上不存在时仍写入(便于首次部署)。
199
+ *
200
+ * @return array<string, bool>
201
+ */
202
+ function readProtectList(): array
203
+ {
204
+ static $cache = null;
205
+ if (is_array($cache)) {
206
+ return $cache;
207
+ }
208
+
209
+ $cache = [];
210
+ $path = PATCH_ROOT . '/PROTECT.txt';
211
+ if (!is_file($path)) {
212
+ return $cache;
213
+ }
214
+
215
+ $lines = file($path, FILE_IGNORE_NEW_LINES);
216
+ if ($lines === false) {
217
+ return $cache;
218
+ }
219
+
220
+ foreach ($lines as $line) {
221
+ $trimmed = trim($line);
222
+ if ($trimmed === '' || str_starts_with($trimmed, '#')) {
223
+ continue;
224
+ }
225
+ $rel = str_replace('\\', '/', $trimmed);
226
+ if (!isSafeRelativePath($rel)) {
227
+ fwrite(STDERR, "忽略 PROTECT.txt 中的不安全路径: {$rel}\n");
228
+ continue;
229
+ }
230
+ $cache[$rel] = true;
231
+ }
232
+
233
+ return $cache;
234
+ }
235
+
236
+ /**
237
+ * 是否在包内保护清单中
238
+ */
239
+ function isProtectListed(string $rel): bool
240
+ {
241
+ $list = readProtectList();
242
+
243
+ return isset($list[str_replace('\\', '/', $rel)]);
244
+ }
245
+
246
+ /**
247
+ * exec 是否可用(disable_functions 可能在堡垒机环境禁用)
248
+ */
249
+ function isExecAvailable(): bool
250
+ {
251
+ if (!function_exists('exec')) {
252
+ return false;
253
+ }
254
+
255
+ $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
256
+
257
+ return !in_array('exec', $disabled, true);
258
+ }
259
+
260
+ /**
261
+ * 读取包内 MODES.txt(可执行文件清单)
262
+ *
263
+ * @return array<string, int> 相对路径 -> 权限(如 0755)
264
+ */
265
+ function readModesList(): array
266
+ {
267
+ static $cache = null;
268
+ if (is_array($cache)) {
269
+ return $cache;
270
+ }
271
+
272
+ $cache = [];
273
+ $path = PATCH_ROOT . '/MODES.txt';
274
+ if (!is_file($path)) {
275
+ return $cache;
276
+ }
277
+
278
+ $lines = file($path, FILE_IGNORE_NEW_LINES);
279
+ if ($lines === false) {
280
+ return $cache;
281
+ }
282
+
283
+ foreach ($lines as $line) {
284
+ $trimmed = trim($line);
285
+ if ($trimmed === '' || str_starts_with($trimmed, '#')) {
286
+ continue;
287
+ }
288
+ if (preg_match('/^([0-7]{3,4})\s+(.+)$/', $trimmed, $m) !== 1) {
289
+ continue;
290
+ }
291
+ $rel = str_replace('\\', '/', trim($m[2]));
292
+ if (!isSafeRelativePath($rel)) {
293
+ continue;
294
+ }
295
+ $cache[$rel] = octdec($m[1]);
296
+ }
297
+
298
+ return $cache;
299
+ }
300
+
301
+ /**
302
+ * 规范化路径用于比较(Windows 不区分大小写)
303
+ */
304
+ function normalizeComparablePath(string $path): string
305
+ {
306
+ $norm = str_replace('\\', '/', rtrim($path, "/\\"));
307
+ if (DIRECTORY_SEPARATOR === '\\') {
308
+ $norm = strtolower($norm);
309
+ }
310
+
311
+ return $norm;
312
+ }
313
+
314
+ /**
315
+ * 判断路径是否位于某个目录之下
316
+ */
317
+ function isPathInside(string $child, string $parent): bool
318
+ {
319
+ $c = normalizeComparablePath($child);
320
+ $p = normalizeComparablePath($parent);
321
+
322
+ return $c === $p || str_starts_with($c . '/', $p . '/');
323
+ }
324
+
325
+ /**
326
+ * 覆盖前校验目标路径:
327
+ * - 目标本身不能是符号链接(避免写到链接指向的任意文件)
328
+ * - 最近的已存在父目录 realpath 必须仍在 Backend 根内(避免父目录软链逃逸)
329
+ */
330
+ function assertTargetInsideBackend(string $backendRoot, string $dst, string $rel): void
331
+ {
332
+ if (is_link($dst)) {
333
+ throw new RuntimeException('目标是符号链接(拒绝覆盖)');
334
+ }
335
+
336
+ $rootReal = realpath($backendRoot);
337
+ if ($rootReal === false) {
338
+ return;
339
+ }
340
+
341
+ $probe = dirname($dst);
342
+ while (!is_dir($probe) && dirname($probe) !== $probe) {
343
+ $probe = dirname($probe);
344
+ }
345
+
346
+ $probeReal = realpath($probe);
347
+ if ($probeReal === false) {
348
+ throw new RuntimeException('无法解析目标父目录');
349
+ }
350
+
351
+ if (!isPathInside($probeReal, $rootReal)) {
352
+ throw new RuntimeException("目标路径越出 Backend 根目录(疑似符号链接): {$rel}");
353
+ }
354
+ }
355
+
356
+ /**
357
+ * 备份会话保留数量(--keep-backups=N / PATCH_KEEP_BACKUPS,默认 10)
358
+ */
359
+ function resolveKeepBackups(): int
360
+ {
361
+ global $argv;
362
+
363
+ foreach ($argv ?? [] as $arg) {
364
+ if (str_starts_with($arg, '--keep-backups=')) {
365
+ $n = (int) substr($arg, strlen('--keep-backups='));
366
+ return $n > 0 ? $n : 10;
367
+ }
368
+ }
369
+
370
+ $fromEnv = getenv('PATCH_KEEP_BACKUPS');
371
+ if (is_string($fromEnv) && preg_match('/^\d+$/', $fromEnv) === 1) {
372
+ $n = (int) $fromEnv;
373
+ return $n > 0 ? $n : 10;
374
+ }
375
+
376
+ return 10;
377
+ }
378
+
379
+ /**
380
+ * 递归删除目录(仅用于清理旧备份会话)
381
+ */
382
+ function removeDirectoryTree(string $dir): bool
383
+ {
384
+ if (!is_dir($dir)) {
385
+ return true;
386
+ }
387
+
388
+ $iterator = new RecursiveIteratorIterator(
389
+ new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
390
+ RecursiveIteratorIterator::CHILD_FIRST
391
+ );
392
+
393
+ foreach ($iterator as $item) {
394
+ $path = $item->getPathname();
395
+ if ($item->isDir() && !$item->isLink()) {
396
+ @rmdir($path);
397
+ } else {
398
+ @unlink($path);
399
+ }
400
+ }
401
+
402
+ return @rmdir($dir);
403
+ }
404
+
405
+ /**
406
+ * 清理超出保留数量的备份会话(含 DEPLOY-META.txt 或本工具写入的会话标记)
407
+ *
408
+ * @param string|null $excludeDir 当前部署刚创建的会话(始终保留)
409
+ * @return list<string> 被删除的会话名
410
+ */
411
+ function pruneBackupSessions(string $backendRoot, int $keep, ?string $excludeDir = null): array
412
+ {
413
+ $backupRoot = resolveBackupRoot($backendRoot);
414
+ if (!is_dir($backupRoot)) {
415
+ return [];
416
+ }
417
+
418
+ /** @var list<array{dir: string, mtime: int}> $sessions */
419
+ $sessions = [];
420
+ /** @var list<array{dir: string, mtime: int}> $incomplete */
421
+ $incomplete = [];
422
+ foreach (scandir($backupRoot) ?: [] as $name) {
423
+ if ($name === '.' || $name === '..') {
424
+ continue;
425
+ }
426
+ $dir = $backupRoot . '/' . $name;
427
+ if (!is_dir($dir)) {
428
+ continue;
429
+ }
430
+ if ($excludeDir !== null && normalizeComparablePath($dir) === normalizeComparablePath($excludeDir)) {
431
+ continue;
432
+ }
433
+
434
+ $item = ['dir' => $dir, 'mtime' => (int) @filemtime($dir)];
435
+ if (is_file($dir . '/' . DEPLOY_META_FILE)) {
436
+ $sessions[] = $item;
437
+ } elseif (is_file($dir . '/' . BACKUP_SESSION_MARKER)) {
438
+ // 中断/旧包的会话:没有元数据,不计入保留数量,单独按时间清理
439
+ $incomplete[] = $item;
440
+ }
441
+ }
442
+
443
+ usort($sessions, static function (array $a, array $b): int {
444
+ $timeA = readDeployMeta($a['dir'])['backed_up_at'] ?? '';
445
+ $timeB = readDeployMeta($b['dir'])['backed_up_at'] ?? '';
446
+ if ($timeA !== $timeB) {
447
+ return $timeA < $timeB ? 1 : -1;
448
+ }
449
+ if ($a['mtime'] !== $b['mtime']) {
450
+ return $b['mtime'] <=> $a['mtime'];
451
+ }
452
+ return strcmp(basename($b['dir']), basename($a['dir']));
453
+ });
454
+
455
+ // 保留数量包含当前会话
456
+ $keepOthers = max(0, max(1, $keep) - ($excludeDir !== null ? 1 : 0));
457
+ /** @var list<string> $removed */
458
+ $removed = [];
459
+ foreach (array_slice($sessions, $keepOthers) as $item) {
460
+ if (removeDirectoryTree($item['dir'])) {
461
+ $removed[] = basename($item['dir']);
462
+ }
463
+ }
464
+
465
+ // 中断会话最多保留 5 个,且只保留最近 24 小时
466
+ $cutoff = time() - 86400;
467
+ usort($incomplete, static function (array $a, array $b): int {
468
+ return $b['mtime'] <=> $a['mtime'];
469
+ });
470
+ foreach ($incomplete as $index => $item) {
471
+ if ($index < 5 && $item['mtime'] >= $cutoff) {
472
+ continue;
473
+ }
474
+ if (removeDirectoryTree($item['dir'])) {
475
+ $removed[] = basename($item['dir']);
476
+ }
477
+ }
478
+
479
+ return $removed;
480
+ }
481
+
482
+ /**
483
+ * 备份目录位于站点根内时,尽量阻止 Web 直接访问(Apache;nginx 需在配置中 deny)
484
+ */
485
+ function protectBackupDir(string $backupRoot): void
486
+ {
487
+ if (!is_dir($backupRoot) && !mkdir($backupRoot, 0755, true) && !is_dir($backupRoot)) {
488
+ return;
489
+ }
490
+
491
+ $htaccess = $backupRoot . '/.htaccess';
492
+ if (!is_file($htaccess)) {
493
+ @file_put_contents(
494
+ $htaccess,
495
+ "# 备份包含历史源码,禁止 Web 访问\n<IfModule mod_authz_core.c>\n Require all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n Deny from all\n</IfModule>\n"
496
+ );
497
+ }
498
+
499
+ $index = $backupRoot . '/index.html';
500
+ if (!is_file($index)) {
501
+ @file_put_contents($index, "Forbidden\n");
502
+ }
503
+ }
504
+
129
505
  /**
130
506
  * 读取 key=value 多行元数据文件(忽略 # 注释行)
131
507
  *
@@ -251,19 +627,27 @@ function createVersionBackupSessionDir(string $backupRoot, ?string $currentVersi
251
627
  throw new RuntimeException("无法创建版本备份目录: {$sessionDir}");
252
628
  }
253
629
 
630
+ markBackupSession($sessionDir);
631
+
254
632
  return $sessionDir;
255
633
  }
256
634
 
257
635
  /**
258
636
  * 写入版本备份元数据
259
637
  *
260
- * @param list<string> $backedUpFiles
638
+ * @param list<string> $backedUpFiles 本次被覆盖的旧文件(已备份到本目录)
639
+ * @param list<array{hash: string, rel: string}> $createdFiles 本次新增的文件(回滚时删除)
640
+ * @param array<string, int> $modes 被覆盖文件的原始权限(回滚时恢复)
641
+ * @param bool $partial 是否来自部分部署(子集包)
261
642
  */
262
643
  function writeDeployMeta(
263
644
  string $backupSessionDir,
264
645
  string $versionLabel,
265
646
  ?string $replacedBy,
266
- array $backedUpFiles
647
+ array $backedUpFiles,
648
+ array $createdFiles = [],
649
+ array $modes = [],
650
+ bool $partial = false
267
651
  ): void {
268
652
  $lines = [
269
653
  'version=' . sanitizeVersionLabel($versionLabel),
@@ -274,15 +658,111 @@ function writeDeployMeta(
274
658
  if ($replacedBy !== null && $replacedBy !== '') {
275
659
  $lines[] = 'replaced_by=' . sanitizeVersionLabel($replacedBy);
276
660
  }
661
+ if ($partial) {
662
+ $lines[] = 'partial=1';
663
+ }
277
664
  $lines[] = '';
278
665
  $lines[] = '# files';
279
666
  foreach ($backedUpFiles as $rel) {
280
667
  $lines[] = $rel;
281
668
  }
282
669
 
670
+ if ($modes !== []) {
671
+ $lines[] = '';
672
+ $lines[] = '# modes';
673
+ foreach ($modes as $rel => $mode) {
674
+ $lines[] = sprintf('%04o %s', $mode, $rel);
675
+ }
676
+ }
677
+
678
+ if ($createdFiles !== []) {
679
+ $lines[] = '';
680
+ $lines[] = '# created';
681
+ foreach ($createdFiles as $item) {
682
+ $lines[] = $item['hash'] . ' ' . $item['rel'];
683
+ }
684
+ }
685
+
283
686
  file_put_contents($backupSessionDir . '/' . DEPLOY_META_FILE, implode("\n", $lines) . "\n");
284
687
  }
285
688
 
689
+ /**
690
+ * 读取 DEPLOY-META 中的 # modes 段(回滚恢复权限)
691
+ *
692
+ * @return array<string, int>
693
+ */
694
+ function readMetaModes(string $backupSessionDir): array
695
+ {
696
+ $path = $backupSessionDir . '/' . DEPLOY_META_FILE;
697
+ if (!is_file($path)) {
698
+ return [];
699
+ }
700
+
701
+ /** @var array<string, int> $modes */
702
+ $modes = [];
703
+ $inModes = false;
704
+
705
+ foreach (file($path, FILE_IGNORE_NEW_LINES) ?: [] as $line) {
706
+ $trimmed = trim($line);
707
+ if ($trimmed === '# modes') {
708
+ $inModes = true;
709
+ continue;
710
+ }
711
+ if ($inModes && str_starts_with($trimmed, '#')) {
712
+ break;
713
+ }
714
+ if ($inModes && preg_match('/^([0-7]{3,4})\s+(.+)$/', $trimmed, $m) === 1) {
715
+ $rel = str_replace('\\', '/', trim($m[2]));
716
+ if (isSafeRelativePath($rel)) {
717
+ $modes[$rel] = octdec($m[1]);
718
+ }
719
+ }
720
+ }
721
+
722
+ return $modes;
723
+ }
724
+
725
+ /**
726
+ * 读取元数据中本次部署新增的文件(用于回滚时删除)
727
+ *
728
+ * @return list<array{hash: string, rel: string}>
729
+ */
730
+ function readMetaCreatedFiles(string $backupSessionDir): array
731
+ {
732
+ $metaPath = $backupSessionDir . '/' . DEPLOY_META_FILE;
733
+ if (!is_file($metaPath)) {
734
+ return [];
735
+ }
736
+
737
+ $lines = file($metaPath, FILE_IGNORE_NEW_LINES);
738
+ if ($lines === false) {
739
+ return [];
740
+ }
741
+
742
+ /** @var list<array{hash: string, rel: string}> $items */
743
+ $items = [];
744
+ $inCreated = false;
745
+
746
+ foreach ($lines as $line) {
747
+ $trimmed = trim($line);
748
+ if ($trimmed === '# created') {
749
+ $inCreated = true;
750
+ continue;
751
+ }
752
+ if ($inCreated && str_starts_with($trimmed, '#')) {
753
+ break;
754
+ }
755
+ if ($inCreated && $trimmed !== '' && preg_match('/^([0-9a-f]{64})\s+(.+)$/i', $trimmed, $m) === 1) {
756
+ $rel = str_replace('\\', '/', trim($m[2]));
757
+ if (isSafeRelativePath($rel)) {
758
+ $items[] = ['hash' => strtolower($m[1]), 'rel' => $rel];
759
+ }
760
+ }
761
+ }
762
+
763
+ return $items;
764
+ }
765
+
286
766
  /**
287
767
  * 读取备份目录元数据
288
768
  *
@@ -317,7 +797,7 @@ function listBackupFiles(string $backupSessionDir): array
317
797
  $abs = $fileInfo->getPathname();
318
798
  $rel = substr($abs, strlen($backupSessionDir) + 1);
319
799
  $relNorm = str_replace('\\', '/', $rel);
320
- if (in_array(basename($relNorm), [DEPLOY_META_FILE, 'MANIFEST.txt'], true)) {
800
+ if (in_array(basename($relNorm), [DEPLOY_META_FILE, BACKUP_SESSION_MARKER, 'MANIFEST.txt'], true)) {
321
801
  continue;
322
802
  }
323
803
  $files[] = $relNorm;
@@ -351,6 +831,10 @@ function listVersionBackups(string $backendRoot): array
351
831
  continue;
352
832
  }
353
833
  $meta = readDeployMeta($dir);
834
+ // 没有元数据的中断会话不列入可回滚版本(仍会被保留策略清理)
835
+ if ($meta === []) {
836
+ continue;
837
+ }
354
838
  $items[] = [
355
839
  'dir' => $dir,
356
840
  'meta' => $meta,
@@ -361,7 +845,16 @@ function listVersionBackups(string $backendRoot): array
361
845
  usort($items, static function (array $a, array $b): int {
362
846
  $timeA = $a['meta']['backed_up_at'] ?? '';
363
847
  $timeB = $b['meta']['backed_up_at'] ?? '';
364
- return $timeA < $timeB ? 1 : -1;
848
+ if ($timeA !== $timeB) {
849
+ return $timeA < $timeB ? 1 : -1;
850
+ }
851
+ $mA = (int) @filemtime($a['dir']);
852
+ $mB = (int) @filemtime($b['dir']);
853
+ if ($mA !== $mB) {
854
+ return $mB <=> $mA;
855
+ }
856
+ // 同秒部署:带 _时间戳 后缀的会话更新,排在基础目录之前
857
+ return strcmp(basename($b['dir']), basename($a['dir']));
365
858
  });
366
859
 
367
860
  return $items;
@@ -377,6 +870,15 @@ function resolveRollbackBackupDir(string $backendRoot, ?string $targetVersion):
377
870
 
378
871
  if ($targetVersion !== null && $targetVersion !== '') {
379
872
  $targetLabel = sanitizeVersionLabel($targetVersion);
873
+
874
+ // 同一版本可能重复部署(目录会追加 _时间戳),取最近一次会话
875
+ foreach (listVersionBackups($backendRoot) as $item) {
876
+ $metaVersion = sanitizeVersionLabel($item['meta']['version'] ?? '');
877
+ if ($metaVersion === $targetLabel) {
878
+ return $item['dir'];
879
+ }
880
+ }
881
+
380
882
  $candidate = $backupRoot . '/' . formatBackupDirName($targetLabel);
381
883
  if (!is_dir($candidate)) {
382
884
  throw new RuntimeException("未找到版本 {$targetLabel} 的备份目录: {$candidate}");
@@ -401,7 +903,9 @@ function resolveRollbackBackupDir(string $backendRoot, ?string $targetVersion):
401
903
  /**
402
904
  * 从版本备份恢复文件
403
905
  *
404
- * @return array{ok: int, fail: int, targetVersion: string}
906
+ * 恢复备份的旧文件;并删除本次部署新增的文件(仅当内容未被修改过)。
907
+ *
908
+ * @return array{ok: int, fail: int, removed: int, kept: int, targetVersion: string}
405
909
  */
406
910
  function rollbackFromBackup(string $backendRoot, string $backupSessionDir): array
407
911
  {
@@ -409,8 +913,14 @@ function rollbackFromBackup(string $backendRoot, string $backupSessionDir): arra
409
913
  $targetVersion = $meta['version'] ?? basename($backupSessionDir);
410
914
  $targetVersion = sanitizeVersionLabel($targetVersion);
411
915
 
916
+ if (($meta['partial'] ?? '') === '1') {
917
+ echo "注意: 该备份来自部分部署(子集包),只会恢复其中的文件。\n";
918
+ }
919
+
412
920
  $files = listBackupFiles($backupSessionDir);
413
- if ($files === []) {
921
+ $createdFiles = readMetaCreatedFiles($backupSessionDir);
922
+ $modes = readMetaModes($backupSessionDir);
923
+ if ($files === [] && $createdFiles === []) {
414
924
  throw new RuntimeException("备份目录无可用文件: {$backupSessionDir}");
415
925
  }
416
926
 
@@ -420,11 +930,15 @@ function rollbackFromBackup(string $backendRoot, string $backupSessionDir): arra
420
930
  $src = $backupSessionDir . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
421
931
  $dst = $backendRoot . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
422
932
  try {
933
+ assertTargetInsideBackend($backendRoot, $dst, $rel);
423
934
  assertTargetWritable($dst, $rel);
424
935
  ensureParentDir($dst);
425
936
  if (!copy($src, $dst)) {
426
937
  throw new RuntimeException('copy 失败');
427
938
  }
939
+ if (isset($modes[$rel])) {
940
+ @chmod($dst, $modes[$rel]);
941
+ }
428
942
  echo "OK {$rel}\n";
429
943
  $ok++;
430
944
  } catch (Throwable $e) {
@@ -433,11 +947,50 @@ function rollbackFromBackup(string $backendRoot, string $backupSessionDir): arra
433
947
  }
434
948
  }
435
949
 
950
+ // 删除本次部署新增的文件;内容已变化则保留现场,避免误删后续改动
951
+ $removed = 0;
952
+ $kept = 0;
953
+ foreach ($createdFiles as $item) {
954
+ $rel = $item['rel'];
955
+ if (isProtectedRelativePath($rel) || isProtectListed($rel)) {
956
+ echo "SKIP {$rel} — 受保护路径\n";
957
+ $kept++;
958
+ continue;
959
+ }
960
+
961
+ $dst = $backendRoot . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
962
+ if (!is_file($dst)) {
963
+ echo "SKIP {$rel} — 已不存在\n";
964
+ continue;
965
+ }
966
+
967
+ $currentHash = @hash_file('sha256', $dst);
968
+ if (!is_string($currentHash) || !hash_equals($item['hash'], $currentHash)) {
969
+ echo "SKIP {$rel} — 部署后已被修改,保留\n";
970
+ $kept++;
971
+ continue;
972
+ }
973
+
974
+ if (@unlink($dst)) {
975
+ echo "DELETED {$rel}\n";
976
+ $removed++;
977
+ } else {
978
+ echo "FAIL-DELETE {$rel} — 无法删除\n";
979
+ $fail++;
980
+ }
981
+ }
982
+
436
983
  if ($fail === 0) {
437
984
  writeDeployedVersion($backendRoot, $targetVersion);
438
985
  }
439
986
 
440
- return ['ok' => $ok, 'fail' => $fail, 'targetVersion' => $targetVersion];
987
+ return [
988
+ 'ok' => $ok,
989
+ 'fail' => $fail,
990
+ 'removed' => $removed,
991
+ 'kept' => $kept,
992
+ 'targetVersion' => $targetVersion,
993
+ ];
441
994
  }
442
995
 
443
996
  /**
@@ -488,11 +1041,17 @@ function listPatchFiles(): array
488
1041
  /** @var list<string> $files */
489
1042
  $files = [];
490
1043
  foreach ($fromManifest as $rel) {
1044
+ if (!isSafeRelativePath($rel)) {
1045
+ throw new RuntimeException("MANIFEST.txt 含不安全路径(拒绝部署): {$rel}");
1046
+ }
491
1047
  $abs = PATCH_ROOT . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
492
1048
  if (!is_file($abs)) {
493
1049
  continue;
494
1050
  }
495
- if (in_array($rel, PROTECTED_RELATIVE, true)) {
1051
+ if (is_link($abs)) {
1052
+ throw new RuntimeException("patch 包内含符号链接(拒绝部署): {$rel}");
1053
+ }
1054
+ if (isProtectedRelativePath($rel)) {
496
1055
  continue;
497
1056
  }
498
1057
  $files[] = $rel;
@@ -515,13 +1074,20 @@ function listPatchFiles(): array
515
1074
  $rel = substr($abs, strlen(PATCH_ROOT) + 1);
516
1075
  $relNorm = str_replace('\\', '/', $rel);
517
1076
 
1077
+ if (!isSafeRelativePath($relNorm)) {
1078
+ throw new RuntimeException("patch 包内含不安全路径(拒绝部署): {$relNorm}");
1079
+ }
1080
+ if ($fileInfo->isLink()) {
1081
+ throw new RuntimeException("patch 包内含符号链接(拒绝部署): {$relNorm}");
1082
+ }
1083
+
518
1084
  if (in_array(basename($relNorm), SKIP_FILES, true)) {
519
1085
  continue;
520
1086
  }
521
1087
  if (in_array($relNorm, SKIP_FILES, true)) {
522
1088
  continue;
523
1089
  }
524
- if (in_array($relNorm, PROTECTED_RELATIVE, true)) {
1090
+ if (isProtectedRelativePath($relNorm)) {
525
1091
  continue;
526
1092
  }
527
1093
 
@@ -544,6 +1110,20 @@ function listPatchFiles(): array
544
1110
  return $files;
545
1111
  }
546
1112
 
1113
+ /**
1114
+ * 输出 MANIFEST-deleted.txt 提示(不自动删除线上文件)
1115
+ */
1116
+ function printDeletedNotice(): void
1117
+ {
1118
+ $deletedList = PATCH_ROOT . '/MANIFEST-deleted.txt';
1119
+ if (!is_file($deletedList)) {
1120
+ return;
1121
+ }
1122
+
1123
+ echo "\n注意: 存在 MANIFEST-deleted.txt,未自动删除线上文件,请人工确认:\n";
1124
+ echo file_get_contents($deletedList);
1125
+ }
1126
+
547
1127
  /**
548
1128
  * 解析 --files / --file-list / PATCH_DEPLOY_FILES,用于单独部署部分文件
549
1129
  *
@@ -642,6 +1222,9 @@ function detectPhpBinary(): string
642
1222
  if (defined('PHP_BINARY') && PHP_BINARY !== '') {
643
1223
  return PHP_BINARY;
644
1224
  }
1225
+ if (!function_exists('shell_exec')) {
1226
+ return 'php';
1227
+ }
645
1228
  $which = trim((string) shell_exec('command -v php 2>/dev/null'));
646
1229
  if ($which !== '') {
647
1230
  return $which;
@@ -754,9 +1337,22 @@ function createBackupSessionDir(string $backupRoot): string
754
1337
  throw new RuntimeException("无法创建备份目录: {$sessionDir}");
755
1338
  }
756
1339
 
1340
+ markBackupSession($sessionDir);
1341
+
757
1342
  return $sessionDir;
758
1343
  }
759
1344
 
1345
+ /**
1346
+ * 标记本工具创建的备份会话(即使部署中断、没有 DEPLOY-META 也能被保留策略清理)
1347
+ */
1348
+ function markBackupSession(string $sessionDir): void
1349
+ {
1350
+ @file_put_contents(
1351
+ $sessionDir . '/' . BACKUP_SESSION_MARKER,
1352
+ "session=1\ncreated_at=" . date('Y-m-d H:i:s') . "\n"
1353
+ );
1354
+ }
1355
+
760
1356
  /**
761
1357
  * 将被覆盖的线上文件复制到备份目录(保持相对路径结构)
762
1358
  *
@@ -824,6 +1420,11 @@ function tryThinkClear(string $backendRoot): void
824
1420
  return;
825
1421
  }
826
1422
 
1423
+ if (!isExecAvailable()) {
1424
+ echo "提示: exec 被 disable_functions 禁用,跳过 php think clear(已清理 runtime/cache)\n";
1425
+ return;
1426
+ }
1427
+
827
1428
  $phpBin = detectPhpBinary();
828
1429
  $cmd = escapeshellarg($phpBin) . ' ' . escapeshellarg($think) . ' clear 2>&1';
829
1430
  $output = [];
@@ -965,13 +1566,24 @@ if ($rollbackOption['enabled']) {
965
1566
 
966
1567
  clearRuntimeCache($backendRoot);
967
1568
  tryThinkClear($backendRoot);
968
- echo "\n已回滚至版本 {$result['targetVersion']}(成功 {$result['ok']} 个文件)\n";
1569
+ echo "\n已回滚至版本 {$result['targetVersion']}(恢复 {$result['ok']} 个文件,删除 {$result['removed']} 个新增文件)\n";
1570
+ if ($result['kept'] > 0) {
1571
+ echo "保留 {$result['kept']} 个新增文件(部署后已修改或受保护)\n";
1572
+ }
969
1573
  exit(0);
970
1574
  }
971
1575
 
972
- $files = listPatchFiles();
1576
+ try {
1577
+ $files = listPatchFiles();
1578
+ } catch (Throwable $e) {
1579
+ fwrite(STDERR, $e->getMessage() . "\n");
1580
+ exit(1);
1581
+ }
1582
+
973
1583
  if ($files === []) {
974
1584
  echo "patch 包内无待部署文件。\n";
1585
+ // 仅含删除项的包没有可部署文件,但仍需提示人工删除
1586
+ printDeletedNotice();
975
1587
  exit(0);
976
1588
  }
977
1589
 
@@ -994,6 +1606,8 @@ $backupEnabled = !$dryRun && !$noBackup;
994
1606
  $patchDeployVersion = resolvePatchDeployVersion();
995
1607
  $currentDeployedVersion = readDeployedVersion($backendRoot);
996
1608
  $versionBackupEnabled = $backupEnabled && $patchDeployVersion !== null;
1609
+ $patchMeta = readKeyValueFile(PATCH_ROOT . '/VERSION.txt');
1610
+ $isPartialDeploy = ($patchMeta['partial'] ?? '') === '1';
997
1611
 
998
1612
  $runUser = function_exists('posix_getpwuid')
999
1613
  ? (posix_getpwuid(posix_geteuid())['name'] ?? 'unknown')
@@ -1007,20 +1621,35 @@ if ($rootCheck['markers'] !== []) {
1007
1621
  }
1008
1622
  echo "\n";
1009
1623
  echo "RUN_AS: {$runUser}\n";
1624
+ if (readProtectList() !== []) {
1625
+ echo 'PROTECT: ' . count(readProtectList()) . " 个文件(线上已存在则跳过覆盖)\n";
1626
+ }
1010
1627
  if ($dryRun) {
1011
1628
  echo "MODE: check-only(不写入文件)\n";
1012
1629
  }
1630
+ if ($isPartialDeploy) {
1631
+ echo "PATCH_MODE: partial(子集包,回滚只覆盖其中的文件)\n";
1632
+ }
1013
1633
  if ($noBackup) {
1014
1634
  echo "BACKUP: disabled(--no-backup)\n";
1015
1635
  } elseif ($versionBackupEnabled) {
1016
1636
  $backupLabel = $currentDeployedVersion ?? 'pre-deploy';
1017
- echo "BACKUP: version -> " . resolveBackupRoot($backendRoot) . '/' . formatBackupDirName($backupLabel) . "/\n";
1637
+ echo "BACKUP: 按当前版本 {$backupLabel} 建立备份会话(重复部署追加时间戳)\n";
1018
1638
  echo "PATCH_VERSION: {$patchDeployVersion}\n";
1019
1639
  echo 'CURRENT_VERSION: ' . ($currentDeployedVersion ?? '(none)') . "\n";
1020
1640
  } elseif ($backupEnabled) {
1021
1641
  echo "BACKUP: timestamp -> " . resolveBackupRoot($backendRoot) . "/<timestamp>/\n";
1022
1642
  }
1023
1643
 
1644
+ if ($backupEnabled) {
1645
+ $backupRootForCheck = resolveBackupRoot($backendRoot);
1646
+ if (isPathInside($backupRootForCheck, $backendRoot)) {
1647
+ echo "WARN: 备份目录位于 Backend 根内({$backupRootForCheck}),历史源码可能被 Web 访问;\n";
1648
+ echo " 建议将 PATCH_BACKUP_DIR 指向站点根外,或在 Web 配置中禁止访问该目录\n";
1649
+ protectBackupDir($backupRootForCheck);
1650
+ }
1651
+ }
1652
+
1024
1653
  try {
1025
1654
  $fileFilter = resolveDeployFileFilter();
1026
1655
  } catch (Throwable $e) {
@@ -1040,23 +1669,42 @@ if ($fileFilter !== null) {
1040
1669
 
1041
1670
  if ($files === []) {
1042
1671
  echo "筛选后无待部署文件。\n";
1672
+ printDeletedNotice();
1043
1673
  exit(0);
1044
1674
  }
1045
1675
 
1046
1676
  $ok = 0;
1047
1677
  $fail = 0;
1678
+ $protectedSkipped = 0;
1048
1679
  $blocked = [];
1049
1680
  $backedUp = 0;
1681
+ $modesList = readModesList();
1682
+ /** @var array<string, int> 被覆盖文件的原始权限(回滚时恢复) */
1683
+ $backedUpModes = [];
1050
1684
  /** @var string|null 本次部署备份会话目录 */
1051
1685
  $backupSessionDir = null;
1052
1686
  /** @var list<string> 已备份文件列表(用于 DEPLOY-META) */
1053
1687
  $backedUpFiles = [];
1688
+ /** @var list<array{hash: string, rel: string}> 本次新增文件(用于回滚删除) */
1689
+ $createdFiles = [];
1054
1690
 
1055
1691
  foreach ($files as $rel) {
1056
1692
  $src = PATCH_ROOT . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
1057
1693
  $dst = $backendRoot . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
1058
1694
 
1059
1695
  try {
1696
+ if (!isSafeRelativePath($rel)) {
1697
+ throw new RuntimeException('路径不安全');
1698
+ }
1699
+
1700
+ // 受保护文件:线上已存在则不覆盖(保留运行时被程序改写的内容)
1701
+ if (isProtectListed($rel) && is_file($dst)) {
1702
+ echo "SKIP {$rel} — 受保护文件(线上已存在,未覆盖)\n";
1703
+ $protectedSkipped++;
1704
+ continue;
1705
+ }
1706
+
1707
+ assertTargetInsideBackend($backendRoot, $dst, $rel);
1060
1708
  assertTargetWritable($dst, $rel);
1061
1709
  if ($dryRun) {
1062
1710
  $existsHint = is_file($dst) ? ',线上已有文件' : '';
@@ -1065,14 +1713,22 @@ foreach ($files as $rel) {
1065
1713
  continue;
1066
1714
  }
1067
1715
 
1068
- // 覆盖前先备份线上旧文件(有 patch 版本标识时用版本目录)
1069
- if ($backupEnabled && is_file($dst)) {
1070
- if ($backupSessionDir === null) {
1071
- $backupRoot = resolveBackupRoot($backendRoot);
1072
- $backupSessionDir = $versionBackupEnabled
1073
- ? createVersionBackupSessionDir($backupRoot, $currentDeployedVersion ?? 'pre-deploy')
1074
- : createBackupSessionDir($backupRoot);
1075
- echo "BACKUP_DIR: {$backupSessionDir}\n";
1716
+ $isNewFile = !is_file($dst);
1717
+
1718
+ // 本次部署的备份会话(覆盖旧文件或新增文件都需要,便于回滚时删除新增文件)
1719
+ if ($backupEnabled && $backupSessionDir === null) {
1720
+ $backupRoot = resolveBackupRoot($backendRoot);
1721
+ $backupSessionDir = $versionBackupEnabled
1722
+ ? createVersionBackupSessionDir($backupRoot, $currentDeployedVersion ?? 'pre-deploy')
1723
+ : createBackupSessionDir($backupRoot);
1724
+ echo "BACKUP_DIR: {$backupSessionDir}\n";
1725
+ }
1726
+
1727
+ // 覆盖前先备份线上旧文件(有 patch 版本标识时用版本目录),并记录原权限
1728
+ if ($backupEnabled && !$isNewFile) {
1729
+ $origMode = @fileperms($dst);
1730
+ if ($origMode !== false) {
1731
+ $backedUpModes[$rel] = $origMode & 0777;
1076
1732
  }
1077
1733
  if (backupExistingFile($dst, $rel, $backupSessionDir)) {
1078
1734
  $backedUp++;
@@ -1084,6 +1740,15 @@ foreach ($files as $rel) {
1084
1740
  if (!copy($src, $dst)) {
1085
1741
  throw new RuntimeException('copy 失败');
1086
1742
  }
1743
+ if (isset($modesList[$rel]) && !@chmod($dst, $modesList[$rel])) {
1744
+ echo "WARN {$rel} — 无法设置权限 0" . decoct($modesList[$rel]) . "\n";
1745
+ }
1746
+ if ($isNewFile) {
1747
+ $hash = @hash_file('sha256', $dst);
1748
+ if (is_string($hash)) {
1749
+ $createdFiles[] = ['hash' => $hash, 'rel' => $rel];
1750
+ }
1751
+ }
1087
1752
  echo "OK {$rel}\n";
1088
1753
  $ok++;
1089
1754
  } catch (Throwable $e) {
@@ -1116,19 +1781,39 @@ if ($fail > 0) {
1116
1781
  }
1117
1782
 
1118
1783
  if ($dryRun) {
1119
- echo "\n检查完成: 可写 {$ok},不可写 {$fail}\n";
1784
+ echo "\n检查完成: 可写 {$ok},不可写 {$fail}";
1785
+ if ($protectedSkipped > 0) {
1786
+ echo ",跳过 {$protectedSkipped}(受保护)";
1787
+ }
1788
+ echo "\n";
1789
+ printDeletedNotice();
1120
1790
  exit($fail > 0 ? 1 : 0);
1121
1791
  }
1122
1792
 
1123
1793
  if ($fail > 0) {
1124
1794
  echo "\n存在写入失败,已跳过清缓存(避免未更新代码却刷新缓存)。\n";
1125
- echo "完成: 成功 {$ok},失败 {$fail}\n";
1795
+ echo "完成: 成功 {$ok},失败 {$fail}";
1796
+ if ($protectedSkipped > 0) {
1797
+ echo ",跳过 {$protectedSkipped}(受保护)";
1798
+ }
1799
+ echo "\n";
1126
1800
  exit(1);
1127
1801
  }
1128
1802
 
1129
- if ($backupSessionDir !== null && $backedUpFiles !== [] && $versionBackupEnabled) {
1803
+ if (
1804
+ $backupSessionDir !== null
1805
+ && $backupEnabled
1806
+ ) {
1130
1807
  $backupVersionLabel = $currentDeployedVersion ?? 'pre-deploy';
1131
- writeDeployMeta($backupSessionDir, $backupVersionLabel, $patchDeployVersion, $backedUpFiles);
1808
+ writeDeployMeta(
1809
+ $backupSessionDir,
1810
+ $backupVersionLabel,
1811
+ $patchDeployVersion,
1812
+ $backedUpFiles,
1813
+ $createdFiles,
1814
+ $backedUpModes,
1815
+ $isPartialDeploy
1816
+ );
1132
1817
  }
1133
1818
 
1134
1819
  clearRuntimeCache($backendRoot);
@@ -1139,6 +1824,16 @@ if ($patchDeployVersion !== null) {
1139
1824
  echo "\nDEPLOY_VERSION: {$patchDeployVersion}\n";
1140
1825
  }
1141
1826
 
1827
+ // 备份会话保留策略(默认 10 个),避免 .deploy-backups 无限增长
1828
+ if ($backupEnabled && $backupSessionDir !== null) {
1829
+ $keepBackups = resolveKeepBackups();
1830
+ $prunedSessions = pruneBackupSessions($backendRoot, $keepBackups, $backupSessionDir);
1831
+ if ($prunedSessions !== []) {
1832
+ echo "\n已清理旧备份会话 " . count($prunedSessions) . " 个(保留最近 {$keepBackups} 个)\n";
1833
+ echo ' 删除: ' . implode(', ', $prunedSessions) . "\n";
1834
+ }
1835
+ }
1836
+
1142
1837
  if ($backupSessionDir !== null) {
1143
1838
  $sampleRel = $backedUpFiles[0] ?? ($files[0] ?? 'path/to/file.php');
1144
1839
  echo "\n已备份 {$backedUp} 个旧文件至: {$backupSessionDir}\n";
@@ -1149,11 +1844,11 @@ if ($backupSessionDir !== null) {
1149
1844
  }
1150
1845
  }
1151
1846
 
1152
- $deletedList = PATCH_ROOT . '/MANIFEST-deleted.txt';
1153
- if (is_file($deletedList)) {
1154
- echo "\n注意: 存在 MANIFEST-deleted.txt,未自动删除线上文件,请人工确认:\n";
1155
- echo file_get_contents($deletedList);
1156
- }
1847
+ printDeletedNotice();
1157
1848
 
1158
- echo "\n完成: 成功 {$ok},失败 {$fail}\n";
1849
+ echo "\n完成: 成功 {$ok},失败 {$fail}";
1850
+ if ($protectedSkipped > 0) {
1851
+ echo ",跳过 {$protectedSkipped}(受保护)";
1852
+ }
1853
+ echo "\n";
1159
1854
  exit($fail > 0 ? 1 : 0);