@cbnventures/nova 0.37.2 → 0.39.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.
Files changed (220) hide show
  1. package/build/package.json +1 -1
  2. package/build/scaffold-versions.json +20 -0
  3. package/build/src/api/app-store-connect.d.ts +17 -2
  4. package/build/src/api/app-store-connect.d.ts.map +1 -1
  5. package/build/src/api/app-store-connect.js +654 -171
  6. package/build/src/api/app-store-connect.js.map +1 -1
  7. package/build/src/api/github-runner-images.d.ts +13 -0
  8. package/build/src/api/github-runner-images.d.ts.map +1 -0
  9. package/build/src/api/github-runner-images.js +238 -0
  10. package/build/src/api/github-runner-images.js.map +1 -0
  11. package/build/src/cli/generate/github/workflows-blueprint-validate.d.ts +2 -2
  12. package/build/src/cli/generate/github/workflows-blueprint-validate.d.ts.map +1 -1
  13. package/build/src/cli/generate/github/workflows-blueprint-validate.js +226 -3
  14. package/build/src/cli/generate/github/workflows-blueprint-validate.js.map +1 -1
  15. package/build/src/cli/generate/github/workflows-blueprint.d.ts +6 -4
  16. package/build/src/cli/generate/github/workflows-blueprint.d.ts.map +1 -1
  17. package/build/src/cli/generate/github/workflows-blueprint.js +804 -124
  18. package/build/src/cli/generate/github/workflows-blueprint.js.map +1 -1
  19. package/build/src/cli/generate/must-haves/agent-conventions.d.ts.map +1 -1
  20. package/build/src/cli/generate/must-haves/agent-conventions.js +1 -0
  21. package/build/src/cli/generate/must-haves/agent-conventions.js.map +1 -1
  22. package/build/src/cli/index.js +13 -1
  23. package/build/src/cli/index.js.map +1 -1
  24. package/build/src/cli/integration/app-store-connect.d.ts +10 -0
  25. package/build/src/cli/integration/app-store-connect.d.ts.map +1 -1
  26. package/build/src/cli/integration/app-store-connect.js +701 -80
  27. package/build/src/cli/integration/app-store-connect.js.map +1 -1
  28. package/build/src/cli/scaffold/app/astro.d.ts.map +1 -1
  29. package/build/src/cli/scaffold/app/astro.js +8 -0
  30. package/build/src/cli/scaffold/app/astro.js.map +1 -1
  31. package/build/src/cli/scaffold/app/discord-bot.d.ts.map +1 -1
  32. package/build/src/cli/scaffold/app/discord-bot.js +28 -0
  33. package/build/src/cli/scaffold/app/discord-bot.js.map +1 -1
  34. package/build/src/cli/scaffold/app/expressjs.d.ts.map +1 -1
  35. package/build/src/cli/scaffold/app/expressjs.js +28 -0
  36. package/build/src/cli/scaffold/app/expressjs.js.map +1 -1
  37. package/build/src/cli/scaffold/app/nextjs.d.ts.map +1 -1
  38. package/build/src/cli/scaffold/app/nextjs.js +22 -0
  39. package/build/src/cli/scaffold/app/nextjs.js.map +1 -1
  40. package/build/src/cli/scaffold/app/vite.d.ts.map +1 -1
  41. package/build/src/cli/scaffold/app/vite.js +8 -0
  42. package/build/src/cli/scaffold/app/vite.js.map +1 -1
  43. package/build/src/cli/scaffold/docs/docusaurus.d.ts.map +1 -1
  44. package/build/src/cli/scaffold/docs/docusaurus.js +8 -0
  45. package/build/src/cli/scaffold/docs/docusaurus.js.map +1 -1
  46. package/build/src/cli/scaffold/package/github-action.d.ts.map +1 -1
  47. package/build/src/cli/scaffold/package/github-action.js +14 -0
  48. package/build/src/cli/scaffold/package/github-action.js.map +1 -1
  49. package/build/src/cli/scaffold/package/homebridge.d.ts.map +1 -1
  50. package/build/src/cli/scaffold/package/homebridge.js +22 -0
  51. package/build/src/cli/scaffold/package/homebridge.js.map +1 -1
  52. package/build/src/cli/scaffold/package/pfsense.d.ts +3 -0
  53. package/build/src/cli/scaffold/package/pfsense.d.ts.map +1 -1
  54. package/build/src/cli/scaffold/package/pfsense.js +148 -6
  55. package/build/src/cli/scaffold/package/pfsense.js.map +1 -1
  56. package/build/src/cli/scaffold/tool/serverless.d.ts +2 -0
  57. package/build/src/cli/scaffold/tool/serverless.d.ts.map +1 -1
  58. package/build/src/cli/scaffold/tool/serverless.js +86 -1
  59. package/build/src/cli/scaffold/tool/serverless.js.map +1 -1
  60. package/build/src/cli/utility/changelog.d.ts +7 -0
  61. package/build/src/cli/utility/changelog.d.ts.map +1 -1
  62. package/build/src/cli/utility/changelog.js +802 -7
  63. package/build/src/cli/utility/changelog.js.map +1 -1
  64. package/build/src/cli/utility/configure.d.ts +6 -1
  65. package/build/src/cli/utility/configure.d.ts.map +1 -1
  66. package/build/src/cli/utility/configure.js +278 -20
  67. package/build/src/cli/utility/configure.js.map +1 -1
  68. package/build/src/cli/utility/run-workspaces.d.ts.map +1 -1
  69. package/build/src/cli/utility/run-workspaces.js +1 -0
  70. package/build/src/cli/utility/run-workspaces.js.map +1 -1
  71. package/build/src/lib/artifact-assembly.d.ts +7 -0
  72. package/build/src/lib/artifact-assembly.d.ts.map +1 -0
  73. package/build/src/lib/artifact-assembly.js +122 -0
  74. package/build/src/lib/artifact-assembly.js.map +1 -0
  75. package/build/src/lib/docker-packaging.d.ts +3 -1
  76. package/build/src/lib/docker-packaging.d.ts.map +1 -1
  77. package/build/src/lib/docker-packaging.js +83 -2
  78. package/build/src/lib/docker-packaging.js.map +1 -1
  79. package/build/src/lib/env-namespace.d.ts.map +1 -1
  80. package/build/src/lib/env-namespace.js +2 -1
  81. package/build/src/lib/env-namespace.js.map +1 -1
  82. package/build/src/lib/item.d.ts +2 -1
  83. package/build/src/lib/item.d.ts.map +1 -1
  84. package/build/src/lib/item.js +18 -0
  85. package/build/src/lib/item.js.map +1 -1
  86. package/build/src/lib/nova-config-order.d.ts.map +1 -1
  87. package/build/src/lib/nova-config-order.js +1 -0
  88. package/build/src/lib/nova-config-order.js.map +1 -1
  89. package/build/src/lib/nova-config.d.ts +1 -0
  90. package/build/src/lib/nova-config.d.ts.map +1 -1
  91. package/build/src/lib/nova-config.js +150 -4
  92. package/build/src/lib/nova-config.js.map +1 -1
  93. package/build/src/lib/regex.d.ts +14 -0
  94. package/build/src/lib/regex.d.ts.map +1 -1
  95. package/build/src/lib/regex.js +14 -0
  96. package/build/src/lib/regex.js.map +1 -1
  97. package/build/src/lib/run-workspaces.d.ts.map +1 -1
  98. package/build/src/lib/run-workspaces.js +79 -8
  99. package/build/src/lib/run-workspaces.js.map +1 -1
  100. package/build/src/lib/scaffold.d.ts +3 -3
  101. package/build/src/lib/scaffold.d.ts.map +1 -1
  102. package/build/src/lib/scaffold.js +140 -8
  103. package/build/src/lib/scaffold.js.map +1 -1
  104. package/build/src/lib/workflow-templates.d.ts +4 -1
  105. package/build/src/lib/workflow-templates.d.ts.map +1 -1
  106. package/build/src/lib/workflow-templates.js +60 -2
  107. package/build/src/lib/workflow-templates.js.map +1 -1
  108. package/build/src/types/api/app-store-connect.d.ts +476 -33
  109. package/build/src/types/api/github-runner-images.d.ts +199 -0
  110. package/build/src/types/cli/generate/github/workflows-blueprint-validate.d.ts +76 -8
  111. package/build/src/types/cli/generate/github/workflows-blueprint.d.ts +178 -11
  112. package/build/src/types/cli/integration/app-store-connect.d.ts +470 -6
  113. package/build/src/types/cli/scaffold/package/pfsense.d.ts +83 -0
  114. package/build/src/types/cli/scaffold/tool/serverless.d.ts +30 -0
  115. package/build/src/types/cli/utility/changelog.d.ts +327 -1
  116. package/build/src/types/cli/utility/configure.d.ts +150 -4
  117. package/build/src/types/lib/artifact-assembly.d.ts +102 -0
  118. package/build/src/types/lib/docker-packaging.d.ts +54 -1
  119. package/build/src/types/lib/env-namespace.d.ts +4 -1
  120. package/build/src/types/lib/item.d.ts +7 -0
  121. package/build/src/types/lib/nova-config.d.ts +91 -2
  122. package/build/src/types/lib/regex.d.ts +91 -0
  123. package/build/src/types/lib/run-workspaces.d.ts +30 -0
  124. package/build/src/types/lib/scaffold.d.ts +67 -4
  125. package/build/src/types/lib/workflow-templates.d.ts +26 -0
  126. package/build/src/types/shared.d.ts +315 -3
  127. package/build/src/types/tests/api/app-store-connect.test.d.ts +162 -0
  128. package/build/src/types/tests/api/github-runner-images.test.d.ts +113 -0
  129. package/build/src/types/tests/cli/generate/github/workflows-blueprint-generate.test.d.ts +19 -0
  130. package/build/src/types/tests/cli/generate/github/workflows-blueprint-parity.test.d.ts +0 -9
  131. package/build/src/types/tests/cli/generate/github/workflows-blueprint-publish-parity.test.d.ts +109 -26
  132. package/build/src/types/tests/cli/generate/github/workflows-blueprint-validate.test.d.ts +146 -30
  133. package/build/src/types/tests/cli/generate/github/workflows-blueprint.test.d.ts +61 -0
  134. package/build/src/types/tests/cli/generate/github/workflows-version-contract.test.d.ts +2 -2
  135. package/build/src/types/tests/cli/generate/must-haves/agent-conventions.test.d.ts +2 -0
  136. package/build/src/types/tests/cli/integration/app-store-connect.test.d.ts +876 -0
  137. package/build/src/types/tests/cli/scaffold/app/nextjs.test.d.ts +6 -0
  138. package/build/src/types/tests/cli/scaffold/tool/serverless.test.d.ts +21 -0
  139. package/build/src/types/tests/cli/utility/changelog-android.test.d.ts +14 -0
  140. package/build/src/types/tests/cli/utility/changelog-apple.test.d.ts +21 -0
  141. package/build/src/types/tests/cli/utility/changelog-fold.test.d.ts +350 -0
  142. package/build/src/types/tests/cli/utility/changelog.test.d.ts +50 -0
  143. package/build/src/types/tests/cli/utility/configure.test.d.ts +56 -0
  144. package/build/src/types/tests/cli/utility/run-workspaces.test.d.ts +29 -2
  145. package/build/src/types/tests/lib/artifact-assembly.test.d.ts +45 -0
  146. package/build/src/types/tests/lib/docker-packaging.test.d.ts +12 -0
  147. package/build/src/types/tests/lib/nova-config-artifacts.test.d.ts +40 -0
  148. package/build/src/types/tests/lib/nova-config.test.d.ts +28 -0
  149. package/build/src/types/tests/lib/scaffold.test.d.ts +59 -2
  150. package/build/src/types/tests/scaffold-output-contract.test.d.ts +79 -0
  151. package/build/templates/generators/must-haves/agent-conventions/AGENTS.md +1 -0
  152. package/build/templates/generators/must-haves/agent-conventions/CLAUDE.md +1 -0
  153. package/build/templates/generators/must-haves/agent-conventions/conventions/nova.md +7 -1
  154. package/build/templates/generators/must-haves/agent-conventions/conventions/pfsense.md +311 -0
  155. package/build/templates/scaffold/app/android/package.json +1 -1
  156. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-ios-1024.png +0 -0
  157. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-128.png +0 -0
  158. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-128@2x.png +0 -0
  159. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-16.png +0 -0
  160. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-16@2x.png +0 -0
  161. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-256.png +0 -0
  162. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-256@2x.png +0 -0
  163. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-32.png +0 -0
  164. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-32@2x.png +0 -0
  165. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-512.png +0 -0
  166. package/build/templates/scaffold/app/apple/Sources/Assets.xcassets/AppIcon.appiconset/AppIcon-mac-512@2x.png +0 -0
  167. package/build/templates/scaffold/app/apple/package.json +1 -1
  168. package/build/templates/scaffold/app/astro/package.json +1 -1
  169. package/build/templates/scaffold/app/discord-bot/package.json +1 -1
  170. package/build/templates/scaffold/app/express/package.json +1 -1
  171. package/build/templates/scaffold/app/nextjs/package.json +1 -1
  172. package/build/templates/scaffold/app/vite/package.json +1 -1
  173. package/build/templates/scaffold/docs/docusaurus/package.json +2 -2
  174. package/build/templates/scaffold/package/github-action/package.json +1 -1
  175. package/build/templates/scaffold/package/homebridge/package.json +1 -1
  176. package/build/templates/scaffold/package/pfsense/package.json +1 -1
  177. package/build/templates/scaffold/package/pfsense/port/Makefile.template +16 -1
  178. package/build/templates/scaffold/package/pfsense/port/files/usr/local/pkg/[__WORKSPACE_NAME__]/FileLock.php +93 -0
  179. package/build/templates/scaffold/package/pfsense/port/files/usr/local/pkg/[__WORKSPACE_NAME__]/PackagePaths.php +40 -0
  180. package/build/templates/scaffold/package/pfsense/port/files/usr/local/pkg/[__WORKSPACE_NAME__]/UpdateManager.php +1667 -0
  181. package/build/templates/scaffold/package/pfsense/port/files/usr/local/pkg/[__WORKSPACE_NAME__].inc +161 -13
  182. package/build/templates/scaffold/package/pfsense/port/files/usr/local/pkg/[__WORKSPACE_NAME__].xml +37 -0
  183. package/build/templates/scaffold/package/pfsense/port/files/usr/local/sbin/[__WORKSPACE_NAME__] +203 -8
  184. package/build/templates/scaffold/package/pfsense/port/files/usr/local/share/pfSense-pkg-[__WORKSPACE_IDENTIFIER__]/logo.svg +12 -0
  185. package/build/templates/scaffold/package/pfsense/port/files/usr/local/share/pfSense-pkg-[__WORKSPACE_IDENTIFIER__]/release-signing.pub +9 -0
  186. package/build/templates/scaffold/package/pfsense/port/files/usr/local/www/[__WORKSPACE_NAME__]-about.php +437 -0
  187. package/build/templates/scaffold/package/pfsense/port/pkg-plist +6 -0
  188. package/build/templates/scaffold/package/pfsense/scripts/build-package.sh +54 -0
  189. package/build/templates/scaffold/package/pfsense/scripts/check-package.mjs +114 -1
  190. package/build/templates/scaffold/package/pfsense/scripts/regex.mjs +10 -0
  191. package/build/templates/scaffold/package/pfsense/tests/updates.php +695 -0
  192. package/build/templates/scaffold-options/app/android-native/app/src/main/res/drawable/ic_launcher_background.xml +1 -1
  193. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-hdpi/ic_launcher.webp +0 -0
  194. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp +0 -0
  195. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-mdpi/ic_launcher.webp +0 -0
  196. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp +0 -0
  197. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-xhdpi/ic_launcher.webp +0 -0
  198. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp +0 -0
  199. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp +0 -0
  200. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp +0 -0
  201. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp +0 -0
  202. package/build/templates/scaffold-options/app/android-native/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp +0 -0
  203. package/build/templates/scaffold-options/docker-image/common/Dockerfile +7 -0
  204. package/build/templates/scaffold-options/tool/serverless/cloudflare-workers/package.json +1 -1
  205. package/build/templates/scaffold-options/tool/serverless/cloudflare-workers/src/types/worker/index.test.d.ts +40 -2
  206. package/build/templates/scaffold-options/tool/serverless/cloudflare-workers/src/types/worker/landing-page.d.ts +23 -0
  207. package/build/templates/scaffold-options/tool/serverless/cloudflare-workers/src/worker/index.test.ts +119 -4
  208. package/build/templates/scaffold-options/tool/serverless/cloudflare-workers/src/worker/index.ts +25 -3
  209. package/build/templates/scaffold-options/tool/serverless/cloudflare-workers/src/worker/landing-page.ts +278 -0
  210. package/build/templates/scaffold-options/tool/serverless/vercel-functions/api/index.test.ts +121 -6
  211. package/build/templates/scaffold-options/tool/serverless/vercel-functions/api/index.ts +49 -12
  212. package/build/templates/scaffold-options/tool/serverless/vercel-functions/package.json +3 -1
  213. package/build/templates/scaffold-options/tool/serverless/vercel-functions/src/function/landing-page.ts +278 -0
  214. package/build/templates/scaffold-options/tool/serverless/vercel-functions/src/types/api/index.d.ts +17 -2
  215. package/build/templates/scaffold-options/tool/serverless/vercel-functions/src/types/api/index.test.d.ts +40 -2
  216. package/build/templates/scaffold-options/tool/serverless/vercel-functions/src/types/function/landing-page.d.ts +23 -0
  217. package/build/templates/scaffold-options/tool/serverless/vercel-functions/tsconfig.functions.json +3 -1
  218. package/build/templates/scaffold-options/tool/serverless/vercel-functions/vercel.json +7 -1
  219. package/package.json +1 -1
  220. package/build/templates/scaffold/package/pfsense-root/.github/workflows/pfsense-[__WORKSPACE_NAME__].yml +0 -62
@@ -0,0 +1,1667 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace PfSense\[__WORKSPACE_IDENTIFIER__]\Runtime;
6
+
7
+ use JsonException;
8
+ use RuntimeException;
9
+ use Throwable;
10
+
11
+ require_once(__DIR__ . '/PackagePaths.php');
12
+
13
+ /**
14
+ * Checks GitHub releases and installs checksum-verified package updates.
15
+ *
16
+ * Scheduled checks, notices, and the About tab share this boundary so release
17
+ * parsing and every verification step remain independently testable.
18
+ *
19
+ * @since UNRELEASED
20
+ */
21
+ final class UpdateManager
22
+ {
23
+ /** GitHub latest-release API endpoint. @since UNRELEASED */
24
+ public const RELEASES_API = '[__PFSENSE_UPDATE_API_URL__]';
25
+
26
+ /** Allowed prefix for release asset URLs returned by GitHub. @since UNRELEASED */
27
+ public const DOWNLOAD_PREFIX = '[__PFSENSE_UPDATE_DOWNLOAD_PREFIX__]';
28
+
29
+ /** Stable pfSense notice identifier for available releases. @since UNRELEASED */
30
+ public const NOTICE_ID = '[__WORKSPACE_NAME__]-update-available';
31
+
32
+ /** Package name recorded in the FreeBSD package manifest. @since UNRELEASED */
33
+ public const PACKAGE_NAME = 'pfSense-pkg-[__WORKSPACE_IDENTIFIER__]';
34
+
35
+ /** Package data directory containing the fallback version metadata. @since UNRELEASED */
36
+ public const PACKAGE_DATA_DIRECTORY = '/usr/local/share/pfSense-pkg-[__WORKSPACE_IDENTIFIER__]';
37
+
38
+ /** Installed OpenSSH public keys trusted for release updates. @since UNRELEASED */
39
+ public const SIGNING_KEYS_FILE = self::PACKAGE_DATA_DIRECTORY . '/release-signing.pub';
40
+
41
+ /** Fixed OpenSSH tool used for release signature verification. @since UNRELEASED */
42
+ public const SSH_KEYGEN_COMMAND = '/usr/bin/ssh-keygen';
43
+
44
+ /** About page linked by the pfSense bell notice. @since UNRELEASED */
45
+ public const ABOUT_PAGE = '/[__WORKSPACE_NAME__]-about.php';
46
+
47
+ /** User agent sent with every GitHub request. @since UNRELEASED */
48
+ private const USER_AGENT = 'pfSense-pkg-[__WORKSPACE_IDENTIFIER__]';
49
+
50
+ /** Largest accepted package release asset in bytes. @since UNRELEASED */
51
+ private const PACKAGE_DOWNLOAD_LIMIT = 64 * 1024 * 1024;
52
+
53
+ /** Largest accepted checksum or signature release asset in bytes. @since UNRELEASED */
54
+ private const AUXILIARY_DOWNLOAD_LIMIT = 64 * 1024;
55
+
56
+ /** Fixed package executable used for metadata checks and installation. @since UNRELEASED */
57
+ private const PKG_COMMAND = '/usr/local/sbin/pkg';
58
+
59
+ /**
60
+ * Creates an update coordinator with production or test-only CLI endpoints.
61
+ *
62
+ * The WebGUI never constructs endpoint overrides. Only the CLI reads the
63
+ * documented test environment variables and passes their values here.
64
+ *
65
+ * @param string $installedVersion - Installed package version.
66
+ * @param string $releasesApi - Latest-release API endpoint.
67
+ * @param string $downloadPrefix - Allowed release asset URL prefix.
68
+ * @param string $updatesFile - Persistent update metadata path.
69
+ * @param string $statusFile - Background update status path.
70
+ * @param string $signingKeysFile - Test-only release signing key path.
71
+ * @param string $sshKeygenCommand - Test-only OpenSSH executable path.
72
+ *
73
+ * @since UNRELEASED
74
+ */
75
+ public function __construct(
76
+ private readonly string $installedVersion,
77
+ private readonly string $releasesApi = self::RELEASES_API,
78
+ private readonly string $downloadPrefix = self::DOWNLOAD_PREFIX,
79
+ private readonly string $updatesFile = PackagePaths::UPDATES_FILE,
80
+ private readonly string $statusFile = PackagePaths::UPDATE_STATUS_FILE,
81
+ private readonly string $signingKeysFile = self::SIGNING_KEYS_FILE,
82
+ private readonly string $sshKeygenCommand = self::SSH_KEYGEN_COMMAND,
83
+ ) {
84
+ }
85
+
86
+ /**
87
+ * Reports whether this generated package has a supported GitHub repository.
88
+ *
89
+ * @return bool
90
+ *
91
+ * @since UNRELEASED
92
+ */
93
+ public static function isAvailable(): bool
94
+ {
95
+ return self::RELEASES_API !== '' && self::DOWNLOAD_PREFIX !== '';
96
+ }
97
+
98
+ /**
99
+ * Confirms the pfSense APIs needed by update operations are available.
100
+ *
101
+ * Fixed system includes provide configuration, proxy, notice, and logging
102
+ * functions without loading the prefix-mutation adapter.
103
+ *
104
+ * @return void
105
+ *
106
+ * @throws RuntimeException When the runtime is not a supported pfSense host.
107
+ *
108
+ * @since UNRELEASED
109
+ */
110
+ public static function assertEnvironment(): void
111
+ {
112
+ if (self::isAvailable() === false) {
113
+ throw new RuntimeException(self::translate('Update checks are unavailable because this package was generated without a github.com repository.'));
114
+ }
115
+
116
+ if (PHP_OS_FAMILY !== 'BSD' || file_exists('/etc/version') === false) {
117
+ throw new RuntimeException(self::translate('[__WORKSPACE_TITLE__] must run on a supported pfSense system.'));
118
+ }
119
+
120
+ $requiredFiles = [
121
+ '/etc/inc/config.inc',
122
+ '/etc/inc/notices.inc',
123
+ '/etc/inc/pfsense-utils.inc',
124
+ ];
125
+
126
+ foreach ($requiredFiles as $requiredFile) {
127
+ if (is_readable($requiredFile) === false) {
128
+ throw new RuntimeException(self::translate('Required pfSense dependency "%1$s" is unavailable.', [$requiredFile]));
129
+ }
130
+
131
+ require_once($requiredFile);
132
+ }
133
+
134
+ $requiredFunctions = [
135
+ 'close_notice',
136
+ 'config_get_path',
137
+ 'file_notice',
138
+ 'log_error',
139
+ 'set_curlproxy',
140
+ ];
141
+
142
+ foreach ($requiredFunctions as $requiredFunction) {
143
+ if (function_exists($requiredFunction) === false) {
144
+ throw new RuntimeException(self::translate('Required pfSense dependency "%1$s" is unavailable.', [$requiredFunction]));
145
+ }
146
+ }
147
+
148
+ if (function_exists('curl_init') === false) {
149
+ throw new RuntimeException(self::translate('The required cURL support is unavailable.'));
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Checks the latest release, saves metadata, and synchronizes the notice.
155
+ *
156
+ * A failed request preserves the last valid release fields while recording a
157
+ * localized error and attempt timestamp for the About tab.
158
+ *
159
+ * @param bool $remoteNotifications - Whether pfSense may notify remote channels.
160
+ *
161
+ * @return array
162
+ *
163
+ * @throws Throwable When GitHub or local state cannot be read or written.
164
+ *
165
+ * @since UNRELEASED
166
+ */
167
+ public function check(bool $remoteNotifications): array
168
+ {
169
+ $this->clearStatus();
170
+
171
+ $state = self::readUpdatesState($this->updatesFile);
172
+ $checkedAt = gmdate(DATE_ATOM);
173
+
174
+ try {
175
+ $release = $this->fetchLatestRelease();
176
+ $state = [
177
+ 'checked_at' => $checkedAt,
178
+ 'latest_version' => $release['version'],
179
+ 'tag' => $release['tag'],
180
+ 'release_url' => $release['release_url'],
181
+ 'published_at' => $release['published_at'],
182
+ 'notified_version' => $state['notified_version'],
183
+ 'last_error' => null,
184
+ ];
185
+ $state = self::synchronizeNotice(
186
+ $state,
187
+ $this->installedVersion,
188
+ $release['version'],
189
+ $remoteNotifications,
190
+ );
191
+
192
+ self::writeJsonAtomically($this->updatesFile, $state);
193
+
194
+ return $state;
195
+ } catch (Throwable $throwable) {
196
+ $state['checked_at'] = $checkedAt;
197
+ $state['last_error'] = $throwable->getMessage();
198
+
199
+ self::writeJsonAtomically($this->updatesFile, $state);
200
+ $this->logFailure($throwable);
201
+
202
+ throw $throwable;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Maps one update frequency to fixed cron fields.
208
+ *
209
+ * The random components are generated once and reused whenever an administrator
210
+ * changes between daily, weekly, and monthly checks.
211
+ *
212
+ * @param string $frequency - Daily, weekly, monthly, or never.
213
+ * @param array $schedule - Stable random schedule values.
214
+ *
215
+ * @return array{string, string, string, string, string}|null
216
+ *
217
+ * @since UNRELEASED
218
+ */
219
+ public static function cronFields(string $frequency, array $schedule): ?array
220
+ {
221
+ $minute = (string) $schedule['minute'];
222
+ $hour = (string) $schedule['hour'];
223
+
224
+ return match ($frequency) {
225
+ 'daily' => [$minute, $hour, '*', '*', '*'],
226
+ 'weekly' => [$minute, $hour, '*', '*', (string) $schedule['weekday']],
227
+ 'monthly' => [$minute, $hour, (string) $schedule['monthday'], '*', '*'],
228
+ 'never' => null,
229
+ default => [$minute, $hour, '*', '*', (string) $schedule['weekday']],
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Returns the installed version using the About tab's two metadata sources.
235
+ *
236
+ * The pfSense installed-package record is authoritative, with the shipped
237
+ * "info.xml" used while that record is unavailable during package lifecycle work.
238
+ *
239
+ * @return string|null
240
+ *
241
+ * @since UNRELEASED
242
+ */
243
+ public static function installedVersion(): ?string
244
+ {
245
+ if (function_exists('config_get_path')) {
246
+ $installedPackages = config_get_path('installedpackages/package', []);
247
+
248
+ if (is_array($installedPackages)) {
249
+ foreach ($installedPackages as $installedPackage) {
250
+ if (!is_array($installedPackage) || ($installedPackage['name'] ?? null) !== '[__WORKSPACE_TITLE__]') {
251
+ continue;
252
+ }
253
+
254
+ $installedPackageVersion = $installedPackage['version'] ?? null;
255
+
256
+ if (is_string($installedPackageVersion) && $installedPackageVersion !== '') {
257
+ return $installedPackageVersion;
258
+ }
259
+ }
260
+ }
261
+ }
262
+
263
+ $packageInfoPath = self::PACKAGE_DATA_DIRECTORY . '/info.xml';
264
+
265
+ if (is_readable($packageInfoPath) === false) {
266
+ return null;
267
+ }
268
+
269
+ if (function_exists('parse_xml_config_pkg') === false) {
270
+ $xmlParserPath = '/etc/inc/xmlparse.inc';
271
+
272
+ if (is_readable($xmlParserPath) === false) {
273
+ return null;
274
+ }
275
+
276
+ require_once($xmlParserPath);
277
+ }
278
+
279
+ $packageInfo = parse_xml_config_pkg($packageInfoPath, 'pfsensepkgs');
280
+ $packageInfoPackage = is_array($packageInfo) ? ($packageInfo['package'] ?? null) : null;
281
+
282
+ if (!is_array($packageInfoPackage)) {
283
+ return null;
284
+ }
285
+
286
+ $packageInfoVersion = $packageInfoPackage['version'] ?? null;
287
+
288
+ if (!is_string($packageInfoVersion)) {
289
+ $packageInfoPackageFirst = $packageInfoPackage[0] ?? null;
290
+ $packageInfoVersion = is_array($packageInfoPackageFirst)
291
+ ? ($packageInfoPackageFirst['version'] ?? null)
292
+ : null;
293
+ }
294
+
295
+ return (is_string($packageInfoVersion) && $packageInfoVersion !== '')
296
+ ? $packageInfoVersion
297
+ : null;
298
+ }
299
+
300
+ /**
301
+ * Validates a release asset URL against the configured repository prefix.
302
+ *
303
+ * Tests may pass a VM endpoint prefix, while production accepts only the fixed
304
+ * GitHub repository download path.
305
+ *
306
+ * @param string $url - Asset URL.
307
+ * @param string $downloadPrefix - Allowed prefix.
308
+ *
309
+ * @return bool
310
+ *
311
+ * @since UNRELEASED
312
+ */
313
+ public static function isAllowedAssetUrl(string $url, string $downloadPrefix = self::DOWNLOAD_PREFIX): bool
314
+ {
315
+ return $downloadPrefix !== '' && str_starts_with($url, $downloadPrefix);
316
+ }
317
+
318
+ /**
319
+ * Validates a release page before the About tab renders it as a link.
320
+ *
321
+ * Only this repository's HTTPS release pages are accepted from persistent state.
322
+ *
323
+ * @param string $url - Release page URL.
324
+ *
325
+ * @return bool
326
+ *
327
+ * @since UNRELEASED
328
+ */
329
+ public static function isAllowedReleaseUrl(string $url): bool
330
+ {
331
+ if (!str_ends_with(self::DOWNLOAD_PREFIX, 'download/')) {
332
+ return false;
333
+ }
334
+
335
+ $releasePagePrefix = substr(self::DOWNLOAD_PREFIX, 0, -strlen('download/'));
336
+
337
+ return $releasePagePrefix !== '' && str_starts_with($url, $releasePagePrefix);
338
+ }
339
+
340
+ /**
341
+ * Compares installed and remote versions after removing one leading "v".
342
+ *
343
+ * GitHub tags use a leading letter while the package manifest stores the semantic
344
+ * version alone, so both inputs are normalized before comparison.
345
+ *
346
+ * @param string $installedVersion - Installed version.
347
+ * @param string $latestVersion - Latest release version or tag.
348
+ *
349
+ * @return bool
350
+ *
351
+ * @since UNRELEASED
352
+ */
353
+ public static function isNewerVersion(string $installedVersion, string $latestVersion): bool
354
+ {
355
+ $normalizedInstalledVersion = self::normalizeVersion($installedVersion);
356
+ $normalizedLatestVersion = self::normalizeVersion($latestVersion);
357
+
358
+ return version_compare($normalizedLatestVersion, $normalizedInstalledVersion, '>');
359
+ }
360
+
361
+ /**
362
+ * Parses and validates GitHub's latest-release response.
363
+ *
364
+ * The normalized result contains only fields needed by checks and installation;
365
+ * malformed external data fails closed before it reaches persistent state.
366
+ *
367
+ * @param string $json - Release JSON.
368
+ *
369
+ * @return array
370
+ *
371
+ * @throws RuntimeException When required release fields are missing or invalid.
372
+ *
373
+ * @since UNRELEASED
374
+ */
375
+ public static function parseReleaseJson(string $json): array
376
+ {
377
+ try {
378
+ $releaseData = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
379
+ } catch (JsonException $jsonException) {
380
+ throw new RuntimeException(self::translate('GitHub returned release metadata that is missing required fields or is not valid JSON.'), 0, $jsonException);
381
+ }
382
+
383
+ if (!is_array($releaseData)) {
384
+ throw new RuntimeException(self::translate('GitHub returned release metadata that is missing required fields or is not valid JSON.'));
385
+ }
386
+
387
+ $tag = $releaseData['tag_name'] ?? null;
388
+ $releaseUrl = $releaseData['html_url'] ?? null;
389
+ $publishedAt = $releaseData['published_at'] ?? null;
390
+ $releaseAssets = $releaseData['assets'] ?? null;
391
+
392
+ if (
393
+ !is_string($tag)
394
+ || $tag === ''
395
+ || !is_string($releaseUrl)
396
+ || self::isAllowedReleaseUrl($releaseUrl) === false
397
+ || !is_string($publishedAt)
398
+ || $publishedAt === ''
399
+ || !is_array($releaseAssets)
400
+ ) {
401
+ throw new RuntimeException(self::translate('GitHub returned release metadata that is missing required fields or is not valid JSON.'));
402
+ }
403
+
404
+ $version = self::normalizeVersion($tag);
405
+
406
+ if (preg_match('/^[0-9]+(?:\.[0-9]+){1,3}(?:[-+][0-9A-Za-z.-]+)?$/', $version) !== 1) {
407
+ throw new RuntimeException(self::translate('The latest GitHub release tag is not a supported package version.'));
408
+ }
409
+
410
+ $assets = [];
411
+
412
+ foreach ($releaseAssets as $releaseAsset) {
413
+ if (!is_array($releaseAsset)) {
414
+ continue;
415
+ }
416
+
417
+ $releaseAssetName = $releaseAsset['name'] ?? null;
418
+ $releaseAssetUrl = $releaseAsset['browser_download_url'] ?? null;
419
+ $releaseAssetDigest = $releaseAsset['digest'] ?? null;
420
+
421
+ if (!is_string($releaseAssetName) || !is_string($releaseAssetUrl)) {
422
+ continue;
423
+ }
424
+
425
+ $assets[] = [
426
+ 'name' => $releaseAssetName,
427
+ 'url' => $releaseAssetUrl,
428
+ 'digest' => is_string($releaseAssetDigest) ? $releaseAssetDigest : null,
429
+ ];
430
+ }
431
+
432
+ return [
433
+ 'tag' => $tag,
434
+ 'version' => $version,
435
+ 'release_url' => $releaseUrl,
436
+ 'published_at' => $publishedAt,
437
+ 'assets' => $assets,
438
+ ];
439
+ }
440
+
441
+ /**
442
+ * Writes a queued state before the WebGUI starts the detached process.
443
+ *
444
+ * This closes the small launch race so the About tab begins polling immediately,
445
+ * even before the background CLI has loaded its runtime classes.
446
+ *
447
+ * @param string|null $version - Version expected from the last check.
448
+ * @param string $path - Status file path.
449
+ *
450
+ * @return void
451
+ *
452
+ * @since UNRELEASED
453
+ */
454
+ public static function queueSelfUpdate(
455
+ ?string $version,
456
+ string $path = PackagePaths::UPDATE_STATUS_FILE,
457
+ ): void {
458
+ $timestamp = gmdate(DATE_ATOM);
459
+
460
+ self::writeJsonAtomically($path, [
461
+ 'state' => 'running',
462
+ 'message' => self::translate('The update is starting.'),
463
+ 'version' => $version,
464
+ 'started_at' => $timestamp,
465
+ 'updated_at' => $timestamp,
466
+ 'finished_at' => null,
467
+ ]);
468
+ }
469
+
470
+ /**
471
+ * Replaces a queued state when the detached CLI cannot begin the update.
472
+ *
473
+ * Environment and lock failures happen before selfUpdate() can write its normal
474
+ * progress states, so the WebGUI needs this terminal state to stop polling.
475
+ *
476
+ * @param string $message - Localized full-sentence failure.
477
+ * @param string $path - Status file path.
478
+ *
479
+ * @return void
480
+ *
481
+ * @since UNRELEASED
482
+ */
483
+ public static function failQueuedSelfUpdate(
484
+ string $message,
485
+ string $path = PackagePaths::UPDATE_STATUS_FILE,
486
+ ): void {
487
+ $timestamp = gmdate(DATE_ATOM);
488
+ $queuedState = null;
489
+
490
+ try {
491
+ $queuedState = self::readStatusState($path);
492
+ } catch (Throwable) {
493
+ // A fresh failure state safely replaces malformed queued state.
494
+ }
495
+
496
+ self::writeJsonAtomically($path, [
497
+ 'state' => 'failed',
498
+ 'message' => $message,
499
+ 'version' => is_array($queuedState) ? ($queuedState['version'] ?? null) : null,
500
+ 'started_at' => is_array($queuedState)
501
+ ? ($queuedState['started_at'] ?? $timestamp)
502
+ : $timestamp,
503
+ 'updated_at' => $timestamp,
504
+ 'finished_at' => $timestamp,
505
+ ]);
506
+ }
507
+
508
+ /**
509
+ * Reads background update status for the About tab and polling request.
510
+ *
511
+ * @param string $path - Status file path.
512
+ *
513
+ * @return array|null
514
+ *
515
+ * @throws RuntimeException When the status file is malformed.
516
+ *
517
+ * @since UNRELEASED
518
+ */
519
+ public static function readStatusState(string $path = PackagePaths::UPDATE_STATUS_FILE): ?array
520
+ {
521
+ if (is_readable($path) === false) {
522
+ return null;
523
+ }
524
+
525
+ return self::readJsonObject($path, self::translate('The saved self-update status is unreadable.'));
526
+ }
527
+
528
+ /**
529
+ * Reads normalized release-check state for CLI and WebGUI callers.
530
+ *
531
+ * @param string $path - Updates file path.
532
+ *
533
+ * @return array
534
+ *
535
+ * @throws RuntimeException When the updates file is malformed.
536
+ *
537
+ * @since UNRELEASED
538
+ */
539
+ public static function readUpdatesState(string $path = PackagePaths::UPDATES_FILE): array
540
+ {
541
+ $state = [
542
+ 'checked_at' => null,
543
+ 'latest_version' => null,
544
+ 'tag' => null,
545
+ 'release_url' => null,
546
+ 'published_at' => null,
547
+ 'notified_version' => null,
548
+ 'last_error' => null,
549
+ ];
550
+
551
+ if (is_readable($path) === false) {
552
+ return $state;
553
+ }
554
+
555
+ $storedState = self::readJsonObject($path, self::translate('The saved update-check state is unreadable.'));
556
+
557
+ foreach (array_keys($state) as $key) {
558
+ $storedValue = $storedState[$key] ?? null;
559
+ $state[$key] = is_string($storedValue) && $storedValue !== '' ? $storedValue : null;
560
+ }
561
+
562
+ return $state;
563
+ }
564
+
565
+ /**
566
+ * Reads the installed OpenSSH Ed25519 release signing keys.
567
+ *
568
+ * A missing or comment-only file keeps unsigned updates compatible. Any
569
+ * malformed content in an existing file fails closed before an asset download.
570
+ *
571
+ * @param string $path - Release signing key file path.
572
+ *
573
+ * @return list<string>
574
+ *
575
+ * @throws RuntimeException When an existing key file is unreadable or malformed.
576
+ *
577
+ * @since UNRELEASED
578
+ */
579
+ public static function readSigningKeys(string $path): array
580
+ {
581
+ if (file_exists($path) === false) {
582
+ return [];
583
+ }
584
+
585
+ if (is_readable($path) === false) {
586
+ throw new RuntimeException(self::translate('The installed release signing key file is unreadable or malformed, so the update was not installed.'));
587
+ }
588
+
589
+ $contents = @file_get_contents($path);
590
+
591
+ if (!is_string($contents)) {
592
+ throw new RuntimeException(self::translate('The installed release signing key file is unreadable or malformed, so the update was not installed.'));
593
+ }
594
+
595
+ $keys = [];
596
+
597
+ foreach (explode("\n", $contents) as $line) {
598
+ $line = trim(str_replace("\r", '', $line));
599
+
600
+ if ($line === '' || str_starts_with($line, '#')) {
601
+ continue;
602
+ }
603
+
604
+ if (
605
+ preg_match(
606
+ '/^ssh-ed25519\s+(AAAAC3NzaC1lZDI1NTE5AAAAI[A-Za-z0-9+\/]{43})(?:\s.*)?$/',
607
+ $line,
608
+ $matches,
609
+ ) !== 1
610
+ ) {
611
+ throw new RuntimeException(self::translate('The installed release signing key file is unreadable or malformed, so the update was not installed.'));
612
+ }
613
+
614
+ $key = $matches[1];
615
+ $decodedKey = base64_decode($key, true);
616
+
617
+ if (!is_string($decodedKey) || strlen($decodedKey) !== 51) {
618
+ throw new RuntimeException(self::translate('The installed release signing key file is unreadable or malformed, so the update was not installed.'));
619
+ }
620
+
621
+ $keys[] = $key;
622
+ }
623
+
624
+ return $keys;
625
+ }
626
+
627
+ /**
628
+ * Builds the OpenSSH allowed-signers file for trusted release keys.
629
+ *
630
+ * Every key is restricted to the package identity and signature namespace so
631
+ * signatures created for another product or purpose cannot authorize an update.
632
+ *
633
+ * @param list<string> $keys - Base64 Ed25519 public key data.
634
+ *
635
+ * @return string
636
+ *
637
+ * @since UNRELEASED
638
+ */
639
+ public static function allowedSignersContent(array $keys): string
640
+ {
641
+ $content = '';
642
+
643
+ foreach ($keys as $key) {
644
+ $content .= self::PACKAGE_NAME
645
+ . ' namespaces="'
646
+ . self::PACKAGE_NAME
647
+ . '" ssh-ed25519 '
648
+ . $key
649
+ . "\n";
650
+ }
651
+
652
+ return $content;
653
+ }
654
+
655
+ /**
656
+ * Selects the versioned package, signature, and trusted SHA-256 source.
657
+ *
658
+ * GitHub's API digest is preferred. A same-release checksum asset is required as
659
+ * the fallback, and every selected URL must remain under the configured prefix.
660
+ *
661
+ * @param array $release - Parsed release.
662
+ * @param string $downloadPrefix - Allowed asset URL prefix.
663
+ *
664
+ * @return array{package: array, digest: string|null, checksum: array|null, signature: array|null}
665
+ *
666
+ * @throws RuntimeException When required assets or their URLs are invalid.
667
+ *
668
+ * @since UNRELEASED
669
+ */
670
+ public static function selectUpdateAssets(
671
+ array $release,
672
+ string $downloadPrefix = self::DOWNLOAD_PREFIX,
673
+ ): array {
674
+ $version = (string) ($release['version'] ?? '');
675
+ $packageAssetName = self::PACKAGE_NAME . '-' . $version . '.pkg';
676
+ $checksumAssetName = $packageAssetName . '.sha256';
677
+ $signatureAssetName = $packageAssetName . '.sig';
678
+ $packageAsset = null;
679
+ $checksumAsset = null;
680
+ $signatureAsset = null;
681
+
682
+ foreach ((is_array($release['assets'] ?? null) ? $release['assets'] : []) as $asset) {
683
+ if (!is_array($asset)) {
684
+ continue;
685
+ }
686
+
687
+ $assetName = $asset['name'] ?? null;
688
+
689
+ if ($assetName === $packageAssetName) {
690
+ $packageAsset = $asset;
691
+ } elseif ($assetName === $checksumAssetName) {
692
+ $checksumAsset = $asset;
693
+ } elseif ($assetName === $signatureAssetName) {
694
+ $signatureAsset = $asset;
695
+ }
696
+ }
697
+
698
+ if (!is_array($packageAsset)) {
699
+ throw new RuntimeException(self::translate('The release does not contain the required package asset %1$s.', [$packageAssetName]));
700
+ }
701
+
702
+ $packageAssetUrl = $packageAsset['url'] ?? null;
703
+
704
+ if (
705
+ !is_string($packageAssetUrl)
706
+ || self::isAllowedAssetUrl($packageAssetUrl, $downloadPrefix) === false
707
+ ) {
708
+ throw new RuntimeException(self::translate('The release contains an asset URL outside the trusted repository path.'));
709
+ }
710
+
711
+ if (is_array($signatureAsset)) {
712
+ $signatureAssetUrl = $signatureAsset['url'] ?? null;
713
+
714
+ if (
715
+ !is_string($signatureAssetUrl)
716
+ || self::isAllowedAssetUrl($signatureAssetUrl, $downloadPrefix) === false
717
+ ) {
718
+ throw new RuntimeException(self::translate('The release contains an asset URL outside the trusted repository path.'));
719
+ }
720
+ }
721
+
722
+ $packageDigest = $packageAsset['digest'] ?? null;
723
+
724
+ if (is_string($packageDigest) && preg_match('/^sha256:[a-fA-F0-9]{64}$/', $packageDigest) === 1) {
725
+ return [
726
+ 'package' => $packageAsset,
727
+ 'digest' => $packageDigest,
728
+ 'checksum' => null,
729
+ 'signature' => $signatureAsset,
730
+ ];
731
+ }
732
+
733
+ if (!is_array($checksumAsset)) {
734
+ throw new RuntimeException(self::translate('The release provides neither a GitHub SHA-256 digest nor the required checksum asset %1$s. The installed version was kept.', [$checksumAssetName]));
735
+ }
736
+
737
+ $checksumAssetUrl = $checksumAsset['url'] ?? null;
738
+
739
+ if (
740
+ !is_string($checksumAssetUrl)
741
+ || self::isAllowedAssetUrl($checksumAssetUrl, $downloadPrefix) === false
742
+ ) {
743
+ throw new RuntimeException(self::translate('The release contains an asset URL outside the trusted repository path.'));
744
+ }
745
+
746
+ return [
747
+ 'package' => $packageAsset,
748
+ 'digest' => null,
749
+ 'checksum' => $checksumAsset,
750
+ 'signature' => $signatureAsset,
751
+ ];
752
+ }
753
+
754
+ /**
755
+ * Verifies one downloaded package against its detached OpenSSH signature.
756
+ *
757
+ * Tests inject a private stub executable, while production always uses the
758
+ * fixed system ssh-keygen path and package identity for both signer and namespace.
759
+ *
760
+ * @param string $packagePath - Downloaded package path.
761
+ * @param string $signaturePath - Downloaded detached signature path.
762
+ * @param list<string> $keys - Trusted base64 Ed25519 key data.
763
+ * @param string $directory - Private directory for allowed signers.
764
+ *
765
+ * @return void
766
+ *
767
+ * @throws RuntimeException When the tool is unavailable or verification fails.
768
+ *
769
+ * @since UNRELEASED
770
+ */
771
+ public function verifyReleaseSignature(
772
+ string $packagePath,
773
+ string $signaturePath,
774
+ array $keys,
775
+ string $directory,
776
+ ): void {
777
+ if (
778
+ is_file($this->sshKeygenCommand) === false
779
+ || is_executable($this->sshKeygenCommand) === false
780
+ ) {
781
+ throw new RuntimeException(self::translate('The required ssh-keygen signature verification tool is unavailable, so the update was not installed.'));
782
+ }
783
+
784
+ $allowedSignersPath = $directory . '/allowed_signers';
785
+ $allowedSignersContent = self::allowedSignersContent($keys);
786
+ $allowedSignersBytes = @file_put_contents(
787
+ $allowedSignersPath,
788
+ $allowedSignersContent,
789
+ LOCK_EX,
790
+ );
791
+
792
+ if (
793
+ $allowedSignersBytes !== strlen($allowedSignersContent)
794
+ || @chmod($allowedSignersPath, 0600) === false
795
+ ) {
796
+ throw new RuntimeException(self::translate('A required package command could not be started.'));
797
+ }
798
+
799
+ $verificationResult = $this->runCommand([
800
+ $this->sshKeygenCommand,
801
+ '-Y',
802
+ 'verify',
803
+ '-f',
804
+ $allowedSignersPath,
805
+ '-I',
806
+ self::PACKAGE_NAME,
807
+ '-n',
808
+ self::PACKAGE_NAME,
809
+ '-s',
810
+ $signaturePath,
811
+ ], $packagePath);
812
+
813
+ if ($verificationResult['exit_code'] !== 0) {
814
+ throw new RuntimeException(self::translate('The release signature does not match this package\'s signing key, so the update was not installed.'));
815
+ }
816
+ }
817
+
818
+ /**
819
+ * Installs the latest release after checksum, signature, and metadata checks pass.
820
+ *
821
+ * The caller owns the package FileLock. This method records progress, invokes
822
+ * "pkg add -f" only after verification, and cleans its private directory.
823
+ *
824
+ * @param bool $remoteNotifications - Whether later notices may reach remote channels.
825
+ *
826
+ * @return array
827
+ *
828
+ * @throws Throwable When any download, verification, metadata, or install step fails.
829
+ *
830
+ * @since UNRELEASED
831
+ */
832
+ public function selfUpdate(bool $remoteNotifications): array
833
+ {
834
+ $temporaryDirectory = null;
835
+ $startedAt = gmdate(DATE_ATOM);
836
+
837
+ $this->writeStatus(
838
+ 'running',
839
+ self::translate('Checking the latest release.'),
840
+ null,
841
+ $startedAt,
842
+ null,
843
+ );
844
+
845
+ try {
846
+ $signingKeys = self::readSigningKeys($this->signingKeysFile);
847
+ $release = $this->fetchLatestRelease();
848
+ $version = $release['version'];
849
+
850
+ if (self::isNewerVersion($this->installedVersion, $version) === false) {
851
+ $state = $this->saveReleaseState($release, $version, $remoteNotifications);
852
+
853
+ $this->writeStatus(
854
+ 'succeeded',
855
+ self::translate('Version %1$s is already installed.', [$version]),
856
+ $version,
857
+ $startedAt,
858
+ gmdate(DATE_ATOM),
859
+ );
860
+
861
+ return $state;
862
+ }
863
+
864
+ $assets = self::selectUpdateAssets($release, $this->downloadPrefix);
865
+
866
+ if (count($signingKeys) > 0 && !is_array($assets['signature'])) {
867
+ $signatureAssetName = $assets['package']['name'] . '.sig';
868
+
869
+ throw new RuntimeException(self::translate(
870
+ 'Release asset %1$s is missing, so the update was not installed.',
871
+ [$signatureAssetName],
872
+ ));
873
+ }
874
+
875
+ $temporaryDirectory = $this->createTemporaryDirectory();
876
+ $packagePath = $temporaryDirectory . '/' . $assets['package']['name'];
877
+
878
+ $this->writeStatus(
879
+ 'running',
880
+ self::translate('Downloading version %1$s and its checksum data.', [$version]),
881
+ $version,
882
+ $startedAt,
883
+ null,
884
+ );
885
+
886
+ $this->downloadFile(
887
+ $assets['package']['url'],
888
+ $packagePath,
889
+ self::PACKAGE_DOWNLOAD_LIMIT,
890
+ );
891
+
892
+ $expectedDigest = $assets['digest'];
893
+
894
+ if (is_array($assets['checksum'])) {
895
+ $checksumPath = $temporaryDirectory . '/' . $assets['checksum']['name'];
896
+
897
+ $this->downloadFile(
898
+ $assets['checksum']['url'],
899
+ $checksumPath,
900
+ self::AUXILIARY_DOWNLOAD_LIMIT,
901
+ );
902
+
903
+ $checksumContents = @file_get_contents($checksumPath);
904
+ $expectedDigest = is_string($checksumContents)
905
+ ? self::checksumDigest($checksumContents)
906
+ : null;
907
+ }
908
+
909
+ $this->writeStatus(
910
+ 'running',
911
+ self::translate('Verifying the SHA-256 checksum and package metadata for version %1$s.', [$version]),
912
+ $version,
913
+ $startedAt,
914
+ null,
915
+ );
916
+
917
+ if (
918
+ !is_string($expectedDigest)
919
+ || self::verifyDigest($packagePath, $expectedDigest) === false
920
+ ) {
921
+ throw new RuntimeException(self::translate('The downloaded package does not match the SHA-256 digest published by GitHub.'));
922
+ }
923
+
924
+ if (count($signingKeys) > 0 && is_array($assets['signature'])) {
925
+ $signaturePath = $temporaryDirectory . '/' . $assets['signature']['name'];
926
+
927
+ $this->downloadFile(
928
+ $assets['signature']['url'],
929
+ $signaturePath,
930
+ self::AUXILIARY_DOWNLOAD_LIMIT,
931
+ );
932
+
933
+ $this->verifyReleaseSignature(
934
+ $packagePath,
935
+ $signaturePath,
936
+ $signingKeys,
937
+ $temporaryDirectory,
938
+ );
939
+ }
940
+
941
+ $this->verifyPackageMetadata($packagePath, $version);
942
+
943
+ $this->writeStatus(
944
+ 'running',
945
+ self::translate('Installing version %1$s with pkg add -f.', [$version]),
946
+ $version,
947
+ $startedAt,
948
+ null,
949
+ );
950
+
951
+ $installResult = $this->runCommand([
952
+ self::PKG_COMMAND,
953
+ 'add',
954
+ '-f',
955
+ $packagePath,
956
+ ]);
957
+
958
+ if ($installResult['exit_code'] !== 0) {
959
+ throw new RuntimeException(self::translate('pkg add -f failed with exit code %1$d. The installed version was not changed successfully.', [$installResult['exit_code']]));
960
+ }
961
+
962
+ $state = $this->saveReleaseState($release, $version, $remoteNotifications);
963
+
964
+ $this->writeStatus(
965
+ 'succeeded',
966
+ self::translate('Version %1$s was installed successfully.', [$version]),
967
+ $version,
968
+ $startedAt,
969
+ gmdate(DATE_ATOM),
970
+ );
971
+
972
+ return $state;
973
+ } catch (Throwable $throwable) {
974
+ $this->writeStatus(
975
+ 'failed',
976
+ $throwable->getMessage(),
977
+ isset($version) && is_string($version) ? $version : null,
978
+ $startedAt,
979
+ gmdate(DATE_ATOM),
980
+ );
981
+ $this->logFailure($throwable);
982
+
983
+ throw $throwable;
984
+ } finally {
985
+ if (is_string($temporaryDirectory)) {
986
+ $this->removeTemporaryDirectory($temporaryDirectory);
987
+ }
988
+ }
989
+ }
990
+
991
+ /**
992
+ * Returns a complete stable randomized cron schedule.
993
+ *
994
+ * Existing valid values win without invoking the random source. Tests inject a
995
+ * deterministic callback; production uses cryptographically secure random_int().
996
+ *
997
+ * @param array $storedSchedule - Previously stored schedule.
998
+ * @param callable|null $randomInteger - Optional integer generator.
999
+ *
1000
+ * @return array{minute: int, hour: int, weekday: int, monthday: int}
1001
+ *
1002
+ * @since UNRELEASED
1003
+ */
1004
+ public static function stableCronSchedule(array $storedSchedule, ?callable $randomInteger = null): array
1005
+ {
1006
+ $ranges = [
1007
+ 'minute' => [0, 59],
1008
+ 'hour' => [0, 23],
1009
+ 'weekday' => [0, 6],
1010
+ 'monthday' => [1, 28],
1011
+ ];
1012
+ $schedule = [];
1013
+ $randomInteger ??= static fn (int $minimum, int $maximum): int => random_int($minimum, $maximum);
1014
+
1015
+ foreach ($ranges as $key => $range) {
1016
+ $storedValue = $storedSchedule[$key] ?? null;
1017
+ $minimum = $range[0];
1018
+ $maximum = $range[1];
1019
+
1020
+ if (
1021
+ (is_int($storedValue) || (is_string($storedValue) && ctype_digit($storedValue)))
1022
+ && (int) $storedValue >= $minimum
1023
+ && (int) $storedValue <= $maximum
1024
+ ) {
1025
+ $schedule[$key] = (int) $storedValue;
1026
+ continue;
1027
+ }
1028
+
1029
+ $schedule[$key] = $randomInteger($minimum, $maximum);
1030
+ }
1031
+
1032
+ return $schedule;
1033
+ }
1034
+
1035
+ /**
1036
+ * Creates or closes the single update notice and records de-duplication state.
1037
+ *
1038
+ * A release can create only one bell notice. Remote notification delivery follows
1039
+ * the explicit checkbox by inverting it for pfSense's local_only argument.
1040
+ *
1041
+ * @param array $state - Update state.
1042
+ * @param string $installedVersion - Installed version.
1043
+ * @param string $latestVersion - Latest version.
1044
+ * @param bool $remoteNotifications - Whether remote delivery is enabled.
1045
+ *
1046
+ * @return array
1047
+ *
1048
+ * @since UNRELEASED
1049
+ */
1050
+ public static function synchronizeNotice(
1051
+ array $state,
1052
+ string $installedVersion,
1053
+ string $latestVersion,
1054
+ bool $remoteNotifications,
1055
+ ): array {
1056
+ if (self::isNewerVersion($installedVersion, $latestVersion) === false) {
1057
+ if (function_exists('close_notice')) {
1058
+ \close_notice(self::NOTICE_ID);
1059
+ }
1060
+
1061
+ return $state;
1062
+ }
1063
+
1064
+ if (($state['notified_version'] ?? null) === $latestVersion) {
1065
+ return $state;
1066
+ }
1067
+
1068
+ $message = self::translate('%1$s %2$s is available.', [
1069
+ self::translate('[__WORKSPACE_TITLE__]'),
1070
+ $latestVersion,
1071
+ ]);
1072
+
1073
+ \file_notice(
1074
+ self::NOTICE_ID,
1075
+ $message,
1076
+ self::translate('[__WORKSPACE_TITLE__]'),
1077
+ self::ABOUT_PAGE,
1078
+ 1,
1079
+ $remoteNotifications === false,
1080
+ );
1081
+
1082
+ $state['notified_version'] = $latestVersion;
1083
+
1084
+ return $state;
1085
+ }
1086
+
1087
+ /**
1088
+ * Converts one checksum-file value into GitHub's digest format.
1089
+ *
1090
+ * Release checksum assets contain only the hexadecimal hash. Whitespace around
1091
+ * that value is accepted, while filenames and other formats fail closed.
1092
+ *
1093
+ * @param string $checksum - Downloaded checksum-file contents.
1094
+ *
1095
+ * @return string|null
1096
+ *
1097
+ * @since UNRELEASED
1098
+ */
1099
+ public static function checksumDigest(string $checksum): ?string
1100
+ {
1101
+ $normalizedChecksum = trim($checksum);
1102
+
1103
+ if (preg_match('/^[a-fA-F0-9]{64}$/', $normalizedChecksum) !== 1) {
1104
+ return null;
1105
+ }
1106
+
1107
+ return 'sha256:' . strtolower($normalizedChecksum);
1108
+ }
1109
+
1110
+ /**
1111
+ * Checks a package file against an expected SHA-256 digest.
1112
+ *
1113
+ * @param string $packagePath - Downloaded package path.
1114
+ * @param string $digest - Expected digest with sha256 prefix.
1115
+ *
1116
+ * @return bool
1117
+ *
1118
+ * @since UNRELEASED
1119
+ */
1120
+ public static function verifyDigest(string $packagePath, string $digest): bool
1121
+ {
1122
+ if (preg_match('/^sha256:([a-fA-F0-9]{64})$/', $digest, $matches) !== 1) {
1123
+ return false;
1124
+ }
1125
+
1126
+ $actualDigest = hash_file('sha256', $packagePath);
1127
+
1128
+ return is_string($actualDigest) && hash_equals(strtolower($matches[1]), strtolower($actualDigest));
1129
+ }
1130
+
1131
+ /**
1132
+ * Removes a completed background status before a standalone check.
1133
+ *
1134
+ * @return void
1135
+ *
1136
+ * @since UNRELEASED
1137
+ * @private
1138
+ */
1139
+ private function clearStatus(): void
1140
+ {
1141
+ if (file_exists($this->statusFile)) {
1142
+ @unlink($this->statusFile);
1143
+ }
1144
+ }
1145
+
1146
+ /**
1147
+ * Creates a private temporary directory for release assets.
1148
+ *
1149
+ * @return string
1150
+ *
1151
+ * @throws RuntimeException When a private directory cannot be created.
1152
+ *
1153
+ * @since UNRELEASED
1154
+ * @private
1155
+ */
1156
+ private function createTemporaryDirectory(): string
1157
+ {
1158
+ try {
1159
+ $suffix = bin2hex(random_bytes(16));
1160
+ } catch (Throwable $throwable) {
1161
+ throw new RuntimeException(self::translate('A private temporary directory for the update could not be created.'), 0, $throwable);
1162
+ }
1163
+
1164
+ $temporaryDirectory = sys_get_temp_dir() . '/[__WORKSPACE_NAME__]-' . $suffix;
1165
+
1166
+ if (mkdir($temporaryDirectory, 0700) === false) {
1167
+ throw new RuntimeException(self::translate('A private temporary directory for the update could not be created.'));
1168
+ }
1169
+
1170
+ return $temporaryDirectory;
1171
+ }
1172
+
1173
+ /**
1174
+ * Downloads one release asset with pfSense proxy and TLS settings.
1175
+ *
1176
+ * @param string $url - Validated asset URL.
1177
+ * @param string $path - Private destination path.
1178
+ * @param int $byteLimit - Maximum accepted download size.
1179
+ *
1180
+ * @return void
1181
+ *
1182
+ * @throws RuntimeException When transport or HTTP validation fails.
1183
+ *
1184
+ * @since UNRELEASED
1185
+ * @private
1186
+ */
1187
+ private function downloadFile(string $url, string $path, int $byteLimit): void
1188
+ {
1189
+ $fileHandle = fopen($path, 'wb');
1190
+
1191
+ if ($fileHandle === false || chmod($path, 0600) === false) {
1192
+ if (is_resource($fileHandle)) {
1193
+ fclose($fileHandle);
1194
+ }
1195
+
1196
+ throw new RuntimeException(self::translate('The release asset could not be downloaded to a private temporary file.'));
1197
+ }
1198
+
1199
+ $curlHandle = curl_init($url);
1200
+
1201
+ if ($curlHandle === false) {
1202
+ fclose($fileHandle);
1203
+
1204
+ throw new RuntimeException(self::translate('The release asset could not be downloaded to a private temporary file.'));
1205
+ }
1206
+
1207
+ $downloadTooLarge = false;
1208
+ $progressCallback = static function (
1209
+ mixed $unusedHandle,
1210
+ float $downloadTotal,
1211
+ float $downloadedCount,
1212
+ float $uploadTotal,
1213
+ float $uploadedCount,
1214
+ ) use (&$downloadTooLarge, $byteLimit): int {
1215
+ if ($downloadedCount > $byteLimit) {
1216
+ $downloadTooLarge = true;
1217
+
1218
+ return 1;
1219
+ }
1220
+
1221
+ return 0;
1222
+ };
1223
+
1224
+ $this->configureCurl($curlHandle, $url, [
1225
+ CURLOPT_FILE => $fileHandle,
1226
+ CURLOPT_HTTPHEADER => [
1227
+ 'Accept: application/octet-stream',
1228
+ ],
1229
+ CURLOPT_MAXFILESIZE_LARGE => $byteLimit,
1230
+ CURLOPT_NOPROGRESS => false,
1231
+ CURLOPT_XFERINFOFUNCTION => $progressCallback,
1232
+ ]);
1233
+
1234
+ $result = curl_exec($curlHandle);
1235
+ $statusCode = (int) curl_getinfo($curlHandle, CURLINFO_RESPONSE_CODE);
1236
+ $curlErrorCode = curl_errno($curlHandle);
1237
+ $curlError = curl_error($curlHandle);
1238
+
1239
+ curl_close($curlHandle);
1240
+ fclose($fileHandle);
1241
+
1242
+ if ($downloadTooLarge || $curlErrorCode === CURLE_FILESIZE_EXCEEDED) {
1243
+ @unlink($path);
1244
+
1245
+ throw new RuntimeException(self::translate('The release asset exceeds the allowed download size, so the update was not installed.'));
1246
+ }
1247
+
1248
+ if ($result !== true || $statusCode < 200 || $statusCode >= 300) {
1249
+ @unlink($path);
1250
+ $detail = $curlError !== '' ? $curlError : (string) $statusCode;
1251
+
1252
+ throw new RuntimeException(self::translate('The release asset download failed: %1$s', [$detail]));
1253
+ }
1254
+ }
1255
+
1256
+ /**
1257
+ * Fetches and parses the latest GitHub release.
1258
+ *
1259
+ * @return array
1260
+ *
1261
+ * @throws RuntimeException When GitHub rejects or rate-limits the request.
1262
+ *
1263
+ * @since UNRELEASED
1264
+ * @private
1265
+ */
1266
+ private function fetchLatestRelease(): array
1267
+ {
1268
+ $responseHeaders = [];
1269
+ $curlHandle = curl_init($this->releasesApi);
1270
+
1271
+ if ($curlHandle === false) {
1272
+ throw new RuntimeException(self::translate('The update check could not initialize a secure GitHub request.'));
1273
+ }
1274
+
1275
+ $headerCallback = static function (mixed $unusedHandle, string $headerLine) use (&$responseHeaders): int {
1276
+ $separatorPosition = strpos($headerLine, ':');
1277
+
1278
+ if ($separatorPosition !== false) {
1279
+ $headerName = strtolower(trim(substr($headerLine, 0, $separatorPosition)));
1280
+ $headerValue = trim(substr($headerLine, $separatorPosition + 1));
1281
+ $responseHeaders[$headerName] = $headerValue;
1282
+ }
1283
+
1284
+ return strlen($headerLine);
1285
+ };
1286
+
1287
+ $this->configureCurl($curlHandle, $this->releasesApi, [
1288
+ CURLOPT_HEADERFUNCTION => $headerCallback,
1289
+ CURLOPT_HTTPHEADER => [
1290
+ 'Accept: application/vnd.github+json',
1291
+ 'X-GitHub-Api-Version: 2022-11-28',
1292
+ ],
1293
+ CURLOPT_RETURNTRANSFER => true,
1294
+ ]);
1295
+
1296
+ $response = curl_exec($curlHandle);
1297
+ $statusCode = (int) curl_getinfo($curlHandle, CURLINFO_RESPONSE_CODE);
1298
+ $curlError = curl_error($curlHandle);
1299
+
1300
+ curl_close($curlHandle);
1301
+
1302
+ if ($response === false) {
1303
+ throw new RuntimeException(self::translate('The update check could not connect to GitHub: %1$s', [$curlError]));
1304
+ }
1305
+
1306
+ if ($statusCode === 403 || $statusCode === 429) {
1307
+ throw new RuntimeException(self::translate('GitHub rate limited the update check. Try again later.'));
1308
+ }
1309
+
1310
+ if ($statusCode < 200 || $statusCode >= 300) {
1311
+ throw new RuntimeException(self::translate('GitHub returned HTTP status %1$d for the update check.', [$statusCode]));
1312
+ }
1313
+
1314
+ if (!is_string($response)) {
1315
+ throw new RuntimeException(self::translate('GitHub returned release metadata that is missing required fields or is not valid JSON.'));
1316
+ }
1317
+
1318
+ return self::parseReleaseJson($response);
1319
+ }
1320
+
1321
+ /**
1322
+ * Applies shared cURL safety, timeout, redirect, and proxy options.
1323
+ *
1324
+ * @param mixed $curlHandle - cURL handle.
1325
+ * @param string $url - Initial request URL.
1326
+ * @param array $options - Operation-specific cURL options.
1327
+ *
1328
+ * @return void
1329
+ *
1330
+ * @since UNRELEASED
1331
+ * @private
1332
+ */
1333
+ private function configureCurl(mixed $curlHandle, string $url, array $options): void
1334
+ {
1335
+ $scheme = parse_url($url, PHP_URL_SCHEME);
1336
+ $allowedProtocols = $scheme === 'http'
1337
+ ? CURLPROTO_HTTP | CURLPROTO_HTTPS
1338
+ : CURLPROTO_HTTPS;
1339
+ $sharedOptions = [
1340
+ CURLOPT_CONNECTTIMEOUT => 5,
1341
+ CURLOPT_FOLLOWLOCATION => true,
1342
+ CURLOPT_MAXREDIRS => 3,
1343
+ CURLOPT_PROTOCOLS => $allowedProtocols,
1344
+ CURLOPT_REDIR_PROTOCOLS => $allowedProtocols,
1345
+ CURLOPT_SSL_VERIFYHOST => 2,
1346
+ CURLOPT_SSL_VERIFYPEER => true,
1347
+ CURLOPT_TIMEOUT => 20,
1348
+ CURLOPT_USERAGENT => self::USER_AGENT,
1349
+ ];
1350
+
1351
+ if (curl_setopt_array($curlHandle, $options + $sharedOptions) === false) {
1352
+ throw new RuntimeException(self::translate('The update check could not initialize a secure GitHub request.'));
1353
+ }
1354
+
1355
+ \set_curlproxy($curlHandle);
1356
+ }
1357
+
1358
+ /**
1359
+ * Logs one safe update failure through pfSense.
1360
+ *
1361
+ * @param Throwable $throwable - Failure to log.
1362
+ *
1363
+ * @return void
1364
+ *
1365
+ * @since UNRELEASED
1366
+ * @private
1367
+ */
1368
+ private function logFailure(Throwable $throwable): void
1369
+ {
1370
+ if (function_exists('log_error')) {
1371
+ \log_error('[__WORKSPACE_TITLE__]: ' . $throwable->getMessage());
1372
+ }
1373
+ }
1374
+
1375
+ /**
1376
+ * Normalizes a package version or Git tag for version_compare().
1377
+ *
1378
+ * @param string $version - Package version or tag.
1379
+ *
1380
+ * @return string
1381
+ *
1382
+ * @since UNRELEASED
1383
+ * @private
1384
+ */
1385
+ private static function normalizeVersion(string $version): string
1386
+ {
1387
+ return preg_replace('/^[vV]/', '', trim($version), 1) ?? trim($version);
1388
+ }
1389
+
1390
+ /**
1391
+ * Reads one JSON object from a package-owned file.
1392
+ *
1393
+ * @param string $path - JSON file path.
1394
+ * @param string $errorMessage - Localized malformed-file message.
1395
+ *
1396
+ * @return array
1397
+ *
1398
+ * @throws RuntimeException When the file cannot be decoded as an object.
1399
+ *
1400
+ * @since UNRELEASED
1401
+ * @private
1402
+ */
1403
+ private static function readJsonObject(string $path, string $errorMessage): array
1404
+ {
1405
+ $contents = @file_get_contents($path);
1406
+
1407
+ if (!is_string($contents)) {
1408
+ throw new RuntimeException($errorMessage);
1409
+ }
1410
+
1411
+ try {
1412
+ $decoded = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
1413
+ } catch (JsonException $jsonException) {
1414
+ throw new RuntimeException($errorMessage, 0, $jsonException);
1415
+ }
1416
+
1417
+ if (!is_array($decoded) || array_is_list($decoded)) {
1418
+ throw new RuntimeException($errorMessage);
1419
+ }
1420
+
1421
+ return $decoded;
1422
+ }
1423
+
1424
+ /**
1425
+ * Removes files from the private update directory and then the directory.
1426
+ *
1427
+ * @param string $temporaryDirectory - Exact generated temporary directory.
1428
+ *
1429
+ * @return void
1430
+ *
1431
+ * @since UNRELEASED
1432
+ * @private
1433
+ */
1434
+ private function removeTemporaryDirectory(string $temporaryDirectory): void
1435
+ {
1436
+ $entries = @scandir($temporaryDirectory);
1437
+
1438
+ foreach ((is_array($entries) ? $entries : []) as $entry) {
1439
+ if ($entry === '.' || $entry === '..') {
1440
+ continue;
1441
+ }
1442
+
1443
+ $entryPath = $temporaryDirectory . '/' . $entry;
1444
+
1445
+ if (is_file($entryPath) || is_link($entryPath)) {
1446
+ @unlink($entryPath);
1447
+ }
1448
+ }
1449
+
1450
+ @rmdir($temporaryDirectory);
1451
+ }
1452
+
1453
+ /**
1454
+ * Runs one fixed executable with separated arguments and captured output.
1455
+ *
1456
+ * @param list<string> $command - Executable and arguments.
1457
+ * @param string|null $stdinPath - Optional file opened as standard input.
1458
+ *
1459
+ * @return array{exit_code: int, stdout: string, stderr: string}
1460
+ *
1461
+ * @throws RuntimeException When the process cannot be started.
1462
+ *
1463
+ * @since UNRELEASED
1464
+ * @private
1465
+ */
1466
+ private function runCommand(array $command, ?string $stdinPath = null): array
1467
+ {
1468
+ $descriptorSpecification = [
1469
+ 0 => is_string($stdinPath) ? ['file', $stdinPath, 'r'] : ['pipe', 'r'],
1470
+ 1 => ['pipe', 'w'],
1471
+ 2 => ['pipe', 'w'],
1472
+ ];
1473
+ $pipes = [];
1474
+ $process = proc_open($command, $descriptorSpecification, $pipes);
1475
+
1476
+ if (!is_resource($process)) {
1477
+ throw new RuntimeException(self::translate('A required package command could not be started.'));
1478
+ }
1479
+
1480
+ if ($stdinPath === null) {
1481
+ fclose($pipes[0]);
1482
+ }
1483
+
1484
+ $standardOutput = stream_get_contents($pipes[1]);
1485
+ $standardError = stream_get_contents($pipes[2]);
1486
+
1487
+ fclose($pipes[1]);
1488
+ fclose($pipes[2]);
1489
+
1490
+ $exitCode = proc_close($process);
1491
+
1492
+ return [
1493
+ 'exit_code' => $exitCode,
1494
+ 'stdout' => is_string($standardOutput) ? $standardOutput : '',
1495
+ 'stderr' => is_string($standardError) ? $standardError : '',
1496
+ ];
1497
+ }
1498
+
1499
+ /**
1500
+ * Saves freshly fetched release metadata after a successful install or no-op.
1501
+ *
1502
+ * @param array $release - Parsed release.
1503
+ * @param string $effectiveVersion - Version treated as installed.
1504
+ * @param bool $remoteNotifications - Whether remote notices are enabled.
1505
+ *
1506
+ * @return array
1507
+ *
1508
+ * @since UNRELEASED
1509
+ * @private
1510
+ */
1511
+ private function saveReleaseState(
1512
+ array $release,
1513
+ string $effectiveVersion,
1514
+ bool $remoteNotifications,
1515
+ ): array {
1516
+ $previousState = self::readUpdatesState($this->updatesFile);
1517
+ $state = [
1518
+ 'checked_at' => gmdate(DATE_ATOM),
1519
+ 'latest_version' => $release['version'],
1520
+ 'tag' => $release['tag'],
1521
+ 'release_url' => $release['release_url'],
1522
+ 'published_at' => $release['published_at'],
1523
+ 'notified_version' => $previousState['notified_version'],
1524
+ 'last_error' => null,
1525
+ ];
1526
+ $state = self::synchronizeNotice(
1527
+ $state,
1528
+ $effectiveVersion,
1529
+ $release['version'],
1530
+ $remoteNotifications,
1531
+ );
1532
+
1533
+ self::writeJsonAtomically($this->updatesFile, $state);
1534
+
1535
+ return $state;
1536
+ }
1537
+
1538
+ /**
1539
+ * Verifies the downloaded archive's package name and version.
1540
+ *
1541
+ * @param string $packagePath - Downloaded package path.
1542
+ * @param string $version - Expected release version.
1543
+ *
1544
+ * @return void
1545
+ *
1546
+ * @throws RuntimeException When pkg reports unexpected metadata.
1547
+ *
1548
+ * @since UNRELEASED
1549
+ * @private
1550
+ */
1551
+ private function verifyPackageMetadata(string $packagePath, string $version): void
1552
+ {
1553
+ $queryResult = $this->runCommand([
1554
+ self::PKG_COMMAND,
1555
+ 'query',
1556
+ '-F',
1557
+ $packagePath,
1558
+ '%n %v',
1559
+ ]);
1560
+ $expectedMetadata = self::PACKAGE_NAME . ' ' . $version;
1561
+ $actualMetadata = trim($queryResult['stdout']);
1562
+
1563
+ if ($queryResult['exit_code'] !== 0 || $actualMetadata !== $expectedMetadata) {
1564
+ throw new RuntimeException(self::translate('The downloaded archive does not contain the expected package name and version.'));
1565
+ }
1566
+ }
1567
+
1568
+ /**
1569
+ * Writes one progress snapshot for the polling About tab.
1570
+ *
1571
+ * @param string $state - Running, succeeded, or failed.
1572
+ * @param string $message - Localized full-sentence status.
1573
+ * @param string|null $version - Release version when known.
1574
+ * @param string $startedAt - Job start timestamp.
1575
+ * @param string|null $finishedAt - Job finish timestamp.
1576
+ *
1577
+ * @return void
1578
+ *
1579
+ * @since UNRELEASED
1580
+ * @private
1581
+ */
1582
+ private function writeStatus(
1583
+ string $state,
1584
+ string $message,
1585
+ ?string $version,
1586
+ string $startedAt,
1587
+ ?string $finishedAt,
1588
+ ): void {
1589
+ self::writeJsonAtomically($this->statusFile, [
1590
+ 'state' => $state,
1591
+ 'message' => $message,
1592
+ 'version' => $version,
1593
+ 'started_at' => $startedAt,
1594
+ 'updated_at' => gmdate(DATE_ATOM),
1595
+ 'finished_at' => $finishedAt,
1596
+ ]);
1597
+ }
1598
+
1599
+ /**
1600
+ * Replaces one JSON file atomically with private permissions.
1601
+ *
1602
+ * @param string $path - Destination path.
1603
+ * @param array $data - JSON object.
1604
+ *
1605
+ * @return void
1606
+ *
1607
+ * @throws RuntimeException When the directory or file cannot be written.
1608
+ *
1609
+ * @since UNRELEASED
1610
+ * @private
1611
+ */
1612
+ private static function writeJsonAtomically(string $path, array $data): void
1613
+ {
1614
+ $directory = dirname($path);
1615
+
1616
+ if (!is_dir($directory) && mkdir($directory, 0700, true) === false) {
1617
+ throw new RuntimeException(self::translate('The update state could not be saved atomically.'));
1618
+ }
1619
+
1620
+ @chmod($directory, 0700);
1621
+
1622
+ $temporaryPath = tempnam($directory, '.update-');
1623
+
1624
+ if ($temporaryPath === false || chmod($temporaryPath, 0600) === false) {
1625
+ throw new RuntimeException(self::translate('The update state could not be saved atomically.'));
1626
+ }
1627
+
1628
+ try {
1629
+ $encoded = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
1630
+ } catch (JsonException $jsonException) {
1631
+ @unlink($temporaryPath);
1632
+
1633
+ throw new RuntimeException(self::translate('The update state could not be saved atomically.'), 0, $jsonException);
1634
+ }
1635
+
1636
+ if (file_put_contents($temporaryPath, $encoded . PHP_EOL, LOCK_EX) === false) {
1637
+ @unlink($temporaryPath);
1638
+
1639
+ throw new RuntimeException(self::translate('The update state could not be saved atomically.'));
1640
+ }
1641
+
1642
+ if (rename($temporaryPath, $path) === false) {
1643
+ @unlink($temporaryPath);
1644
+
1645
+ throw new RuntimeException(self::translate('The update state could not be saved atomically.'));
1646
+ }
1647
+
1648
+ @chmod($path, 0600);
1649
+ }
1650
+ /**
1651
+ * Translates one operator-visible message through pfSense gettext.
1652
+ *
1653
+ * @param string $message - English source message.
1654
+ * @param array<int, scalar> $arguments - Positional sprintf arguments.
1655
+ *
1656
+ * @return string
1657
+ *
1658
+ * @since UNRELEASED
1659
+ * @private
1660
+ */
1661
+ private static function translate(string $message, array $arguments = []): string
1662
+ {
1663
+ $translated = function_exists('gettext') ? \gettext($message) : $message;
1664
+
1665
+ return $arguments === [] ? $translated : vsprintf($translated, $arguments);
1666
+ }
1667
+ }