farming-code 2.2.28 → 2.2.30

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 (83) hide show
  1. package/README.md +27 -90
  2. package/README.zh_cn.md +17 -90
  3. package/THIRD_PARTY_NOTICES.md +25 -6
  4. package/backend/acp/packaged-claude-acp.js +13 -0
  5. package/backend/acp/packaged-codex-acp.js +2 -2
  6. package/backend/acp-runtime.js +38 -17
  7. package/backend/acp-session-state.js +78 -88
  8. package/backend/acp-transcript.js +174 -9
  9. package/backend/agent-manager.js +27 -2
  10. package/backend/agent-session-history.js +45 -12
  11. package/backend/codex-session-history.js +1 -1
  12. package/backend/codex-transcript.js +0 -202
  13. package/backend/config-manager.js +44 -16
  14. package/backend/data/LICENSE.agent-browser +201 -0
  15. package/backend/data/runtime-dependency-manifest.json +199 -0
  16. package/backend/data/runtime-dependency-sources.json +5 -0
  17. package/backend/executable-discovery.js +7 -0
  18. package/backend/farming-agent-bootstrap.zh_cn.md +4 -2
  19. package/backend/farming-app-cli.js +161 -65
  20. package/backend/farming-cli.js +7 -59
  21. package/backend/index-html.js +31 -0
  22. package/backend/main-agent-skills.js +7 -28
  23. package/backend/npm-update-helper.js +43 -6
  24. package/backend/provider-adapters.js +10 -0
  25. package/backend/runtime-dependency-manager.js +759 -0
  26. package/backend/runtime-executable-invocation.js +20 -0
  27. package/backend/server-process-identity.js +47 -0
  28. package/backend/server.js +145 -204
  29. package/backend/slash-command-discovery.js +138 -1
  30. package/backend/storage-layout.js +30 -0
  31. package/backend/update-service.js +60 -914
  32. package/config/farming.deploy.env.example +1 -1
  33. package/config/farming.install.env.example +5 -1
  34. package/dist/acp/LICENSE.claude-agent-acp +191 -0
  35. package/dist/acp/LICENSE.claude-agent-sdk +1 -0
  36. package/dist/acp/claude-agent-acp-0.59.0.mjs +41606 -0
  37. package/dist/acp/{codex-acp-1.1.4.js → codex-acp-1.1.4.mjs} +387 -7
  38. package/dist/assets/{App-CM7Cy-l4.css → App-BKNUILuL.css} +1 -1
  39. package/dist/assets/App-Z1N7T0eM.js +695 -0
  40. package/dist/assets/{FileEditorMarkdownPreview-DYOMm-b1.js → FileEditorMarkdownPreview-Cs9cLv8a.js} +1 -1
  41. package/dist/assets/FileEditorPane-CNtuGjQ3.js +2 -0
  42. package/dist/assets/IconGlyphs-BClgag6E.js +1 -0
  43. package/dist/assets/ProjectFilesSection-K3GHuQ4U.js +12 -0
  44. package/dist/assets/ReviewPage-BRuxFaH5.js +3 -0
  45. package/dist/assets/code-dark-kLsQLvpf.css +1 -0
  46. package/dist/assets/{index-BzQO3pUr.js → index-D-zetSol.js} +2 -2
  47. package/dist/assets/main-DUTz-Rd2.css +1 -0
  48. package/dist/assets/{workspace-editor-monaco-tXA-udGx.js → workspace-editor-monaco-CJNwbpCy.js} +1 -1
  49. package/dist/assets/workspace-editor-monaco-CO9w8YV0.js +1 -0
  50. package/dist/assets/workspace-view-state-BjKPYp0E.js +7 -0
  51. package/dist/index.html +33 -3
  52. package/extensions/browser/backend/agent-browser-runtime.js +1041 -0
  53. package/extensions/browser/backend/browser-mcp-server.js +352 -0
  54. package/extensions/browser/backend/browser-resource-manager.js +921 -114
  55. package/extensions/browser/backend/browser-resource-store.js +47 -6
  56. package/extensions/browser/backend/browser-router.js +15 -2
  57. package/extensions/browser/backend/executable-discovery.js +164 -17
  58. package/extensions/browser/backend/managed-chromium-installer.js +593 -0
  59. package/extensions/browser/bin/farming-browser +384 -30
  60. package/extensions/browser/frontend/BrowserSidebarPortals.tsx +17 -19
  61. package/extensions/browser/frontend/BrowserViewer.tsx +217 -46
  62. package/extensions/browser/frontend/browser.css +68 -17
  63. package/extensions/browser/frontend/types.ts +13 -0
  64. package/extensions/browser/frontend/useBrowserResources.ts +18 -3
  65. package/index.html +32 -2
  66. package/package.json +10 -6
  67. package/shared/backend-connection-status.d.ts +12 -0
  68. package/shared/backend-connection-status.js +35 -4
  69. package/backend/agent-activity.js +0 -35
  70. package/backend/agent-memory-report.js +0 -583
  71. package/backend/bundle-update-helper.js +0 -113
  72. package/backend/codex-rollout-follower.js +0 -326
  73. package/dist/assets/App-CPG4WcjO.js +0 -658
  74. package/dist/assets/FileEditorPane-DXXq82aM.js +0 -2
  75. package/dist/assets/IconGlyphs-DrdPjYXr.js +0 -1
  76. package/dist/assets/ProjectFilesSection-CP66XVPl.js +0 -12
  77. package/dist/assets/ReviewPage-w21MEPD6.js +0 -3
  78. package/dist/assets/code-dark-BDjwj7Um.css +0 -1
  79. package/dist/assets/main-BlVUXfxa.css +0 -1
  80. package/dist/assets/workspace-editor-monaco-CFEfFNcA.js +0 -1
  81. package/dist/assets/workspace-view-state-BS_V8JVs.js +0 -7
  82. package/extensions/browser/backend/cdp-browser-runtime.js +0 -648
  83. package/extensions/browser/backend/cdp-client.js +0 -167
@@ -1,16 +1,13 @@
1
1
  const childProcess = require('child_process');
2
- const crypto = require('crypto');
3
2
  const fs = require('fs');
4
3
  const http = require('http');
5
4
  const https = require('https');
6
5
  const os = require('os');
7
6
  const path = require('path');
8
- const { Transform } = require('stream');
9
- const { pipeline } = require('stream/promises');
7
+ const { readServerProcessIdentity } = require('./server-process-identity');
10
8
  const storageLayout = require('./storage-layout');
11
9
 
12
10
  const CACHE_TTL_MS = 5 * 60 * 1000;
13
- const UPDATE_SOURCE_UNCONFIGURED_REASON = 'Update source is empty. Save an Update URL in Settings or restore the default source.';
14
11
  const NPM_PACKAGE_NAME = 'farming-code';
15
12
  const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
16
13
 
@@ -65,102 +62,18 @@ function detectInstallMethod(rootDir, options = {}) {
65
62
  return 'source';
66
63
  }
67
64
 
68
- function installMethodAllowsBundleUpdate(method) {
69
- return method === 'app-bundle' || method === 'source-deploy';
70
- }
71
-
72
65
  function installMethodBlockedReason(method) {
73
66
  if (method === 'source') return 'Source checkouts update through Git, not the in-app updater';
67
+ if (method === 'source-deploy') return 'Source deployments update through their deployment workflow, not the in-app updater';
68
+ if (method === 'app-bundle') return 'App bundles update by reinstalling a release package or switching to npm';
74
69
  if (method === 'standalone-cli') return 'Standalone CLI updates must reinstall the matching release asset';
75
- return `In-app updates are not supported for ${method || 'this installation'}`;
70
+ return `In-app updates require an npm installation; reinstall ${method || 'this installation'} through npm`;
76
71
  }
77
72
 
78
73
  function hasComparableVersion(value) {
79
74
  return versionParts(value).length > 0;
80
75
  }
81
76
 
82
- function releaseVersionFromAsset(asset) {
83
- return normalizeVersion(asset && (
84
- asset.releaseVersion ||
85
- asset.version ||
86
- asset.file ||
87
- asset.name ||
88
- basenameFromUrl(asset.browser_download_url || asset.downloadUrl || asset.url)
89
- ));
90
- }
91
-
92
- function releaseVersionFromRelease(release) {
93
- const taggedVersion = normalizeVersion(release && (release.tag_name || release.name));
94
- if (hasComparableVersion(taggedVersion)) return taggedVersion;
95
- const assetVersion = releaseVersionFromAsset(selectReleaseAsset(release));
96
- return hasComparableVersion(assetVersion) ? assetVersion : taggedVersion;
97
- }
98
-
99
- function releaseVersionFromManifest(manifest) {
100
- if (!manifest) return '';
101
- if (manifest.version) return normalizeVersion(manifest.version);
102
- if (manifest.releaseVersion) return normalizeVersion(manifest.releaseVersion);
103
- if (manifest.tag) return normalizeVersion(manifest.tag);
104
- const assets = manifestAssets(manifest);
105
- const appBundle = assets.find(asset => asset && asset.type === 'app-bundle') || assets[0];
106
- return releaseVersionFromAsset(appBundle);
107
- }
108
-
109
- function releaseTagFromManifest(manifest) {
110
- const tag = String(manifest && manifest.tag || '').trim();
111
- if (tag) return tag;
112
- const version = releaseVersionFromManifest(manifest);
113
- return version ? `v${version}` : '';
114
- }
115
-
116
- function isAbsoluteHttpUrl(value) {
117
- return /^https?:\/\//i.test(String(value || ''));
118
- }
119
-
120
- function resolveUpdateUrl(value, baseUrl = '') {
121
- const raw = String(value || '').trim();
122
- if (!raw) return '';
123
- if (isAbsoluteHttpUrl(raw)) return raw;
124
- if (!baseUrl) return '';
125
- try {
126
- return new URL(raw, baseUrl).toString();
127
- } catch {
128
- return '';
129
- }
130
- }
131
-
132
- function basenameFromUrl(value) {
133
- const raw = String(value || '').trim();
134
- if (!raw) return '';
135
- try {
136
- const parsed = isAbsoluteHttpUrl(raw) ? new URL(raw) : new URL(raw, 'http://farming.local/');
137
- const pathname = parsed.pathname || '';
138
- return pathname.split('/').filter(Boolean).pop() || '';
139
- } catch {
140
- return raw.split('/').filter(Boolean).pop() || '';
141
- }
142
- }
143
-
144
- function manifestAssets(manifest) {
145
- if (Array.isArray(manifest && manifest.assets)) return manifest.assets;
146
- const tarUrl = manifest && (manifest.tarUrl || manifest.downloadUrl || manifest.url);
147
- const file = manifest && (manifest.file || manifest.name || basenameFromUrl(tarUrl));
148
- if (!tarUrl && !file) return [];
149
- return [{
150
- type: 'app-bundle',
151
- file,
152
- url: tarUrl,
153
- size: manifest.size || manifest.bytes || 0,
154
- sha256: manifest.sha256 || '',
155
- releaseVersion: manifest.releaseVersion || manifest.version || '',
156
- }];
157
- }
158
-
159
- function normalizeSha256(value) {
160
- const normalized = String(value || '').trim().toLowerCase();
161
- return /^[a-f0-9]{64}$/.test(normalized) ? normalized : '';
162
- }
163
-
164
77
  function normalizePlatform(value) {
165
78
  const raw = String(value || '').trim().toLowerCase();
166
79
  if (raw === 'darwin' || raw === 'macos' || raw === 'macosx' || raw === 'osx') return 'darwin';
@@ -175,174 +88,6 @@ function normalizeArch(value) {
175
88
  return raw;
176
89
  }
177
90
 
178
- function assetMatchesRuntime(asset, runtime) {
179
- if (!runtime) return true;
180
- return normalizePlatform(asset && asset.platform) === runtime.platform
181
- && normalizeArch(asset && asset.arch) === runtime.arch;
182
- }
183
-
184
- function assetCompatibilityPreference(asset, preferredProfile = '') {
185
- const profile = String(asset && asset.compatibilityProfile || '').trim();
186
- const preferred = String(preferredProfile || '').trim();
187
- if (preferred) return profile === preferred ? 0 : 1;
188
- return profile ? 1 : 0;
189
- }
190
-
191
- function runtimeFromBundleName(value) {
192
- const match = /-(darwin|linux)-(x64|arm64)\.tar\.gz$/i.exec(String(value || ''));
193
- return match ? { platform: normalizePlatform(match[1]), arch: normalizeArch(match[2]) } : null;
194
- }
195
-
196
- function releaseFromAssetListing(release) {
197
- const rawAssets = Array.isArray(release && release.assets) ? release.assets : [];
198
- const checksumAsset = rawAssets.find(asset => /(?:checksums?|sha256)\.(?:txt|sha256)$/i.test(String(asset && asset.name || '')));
199
- return {
200
- ...release,
201
- __directAssets: true,
202
- assets: rawAssets.map(asset => {
203
- const runtime = runtimeFromBundleName(asset && asset.name);
204
- const isBundle = /^farming[-_].*\.tar\.gz$/i.test(String(asset && asset.name || ''));
205
- return {
206
- ...asset,
207
- ...(isBundle ? { type: 'app-bundle' } : {}),
208
- ...(runtime || {}),
209
- ...(checksumAsset?.browser_download_url ? { checksum_url: checksumAsset.browser_download_url } : {}),
210
- };
211
- }),
212
- };
213
- }
214
-
215
- function releaseFromManifest(manifest, options = {}) {
216
- const tag = releaseTagFromManifest(manifest);
217
- const assetBaseUrl = options.assetBaseUrl || options.manifestUrl || '';
218
- const assets = manifestAssets(manifest);
219
- return {
220
- __manifest: manifest,
221
- tag_name: tag,
222
- name: manifest && manifest.name ? String(manifest.name) : tag,
223
- published_at: manifest && (manifest.publishedAt || manifest.builtAt) ? String(manifest.publishedAt || manifest.builtAt) : '',
224
- assets: assets
225
- .map(asset => {
226
- const file = String(asset && (
227
- asset.file ||
228
- asset.name ||
229
- basenameFromUrl(asset.browser_download_url || asset.downloadUrl || asset.url)
230
- ) || '');
231
- if (!file) return null;
232
- return {
233
- ...asset,
234
- name: file,
235
- size: asset.size || asset.bytes || 0,
236
- browser_download_url: asset.browser_download_url
237
- || resolveUpdateUrl(asset.downloadUrl || asset.url || file, assetBaseUrl),
238
- };
239
- })
240
- .filter(asset => asset && asset.browser_download_url),
241
- };
242
- }
243
-
244
- function selectReleaseAsset(release, patternText = '') {
245
- const assets = Array.isArray(release && release.assets) ? release.assets : [];
246
- if (patternText) {
247
- const pattern = new RegExp(patternText);
248
- const matched = assets.find(asset => pattern.test(String(asset.name || '')) && asset.browser_download_url);
249
- if (matched) return matched;
250
- }
251
-
252
- return assets.find(asset => (
253
- /^farming[-_].*\.tar\.gz$/i.test(String(asset.name || '')) &&
254
- !/(sha256|checksum|checksums)/i.test(String(asset.name || '')) &&
255
- asset.browser_download_url
256
- )) || null;
257
- }
258
-
259
- function releaseAssetVersion(asset, fallbackVersion = '') {
260
- return normalizeVersion(
261
- asset && (asset.releaseVersion || asset.version || asset.name || asset.file || asset.browser_download_url) ||
262
- fallbackVersion
263
- );
264
- }
265
-
266
- function selectableReleaseAssets(release, patternText = '', runtime = null, preferredCompatibilityProfile = '') {
267
- const assets = Array.isArray(release && release.assets) ? release.assets : [];
268
- const pattern = patternText ? new RegExp(patternText) : null;
269
- return assets
270
- .filter(asset => (
271
- /^farming[-_].*\.tar\.gz$/i.test(String(asset.name || '')) &&
272
- !/(sha256|checksum|checksums)/i.test(String(asset.name || '')) &&
273
- asset.browser_download_url &&
274
- assetMatchesRuntime(asset, runtime) &&
275
- (!preferredCompatibilityProfile || String(asset.compatibilityProfile || '').trim() === preferredCompatibilityProfile) &&
276
- (!pattern || pattern.test(String(asset.name || '')))
277
- ))
278
- .sort((left, right) => (
279
- compareVersions(releaseAssetVersion(right), releaseAssetVersion(left)) ||
280
- assetCompatibilityPreference(left, preferredCompatibilityProfile) - assetCompatibilityPreference(right, preferredCompatibilityProfile) ||
281
- String(right.name || '').localeCompare(String(left.name || ''))
282
- ));
283
- }
284
-
285
- function selectReleaseAssetByName(release, assetName, patternText = '', runtime = null, preferredCompatibilityProfile = '') {
286
- const wanted = String(assetName || '').trim();
287
- if (!wanted) return selectableReleaseAssets(release, patternText, runtime, preferredCompatibilityProfile)[0] || null;
288
- return selectableReleaseAssets(release, patternText, runtime, preferredCompatibilityProfile)
289
- .find(asset => String(asset.name || '') === wanted) || null;
290
- }
291
-
292
- function selectManifestAsset(release) {
293
- const assets = Array.isArray(release && release.assets) ? release.assets : [];
294
- return assets.find(asset => (
295
- String(asset.name || '').toLowerCase() === 'manifest.json' &&
296
- asset.browser_download_url
297
- )) || null;
298
- }
299
-
300
- function manifestAssetSafety(asset, manifest, options = {}) {
301
- const runtime = options.runtime || null;
302
- if (!asset) {
303
- return {
304
- safe: false,
305
- reason: 'Update manifest has no app bundle asset',
306
- };
307
- }
308
- const assets = manifestAssets(manifest);
309
- if (assets.length === 0 && !asset.checksum_url && !asset.checksumUrl && !asset.sha256) {
310
- return {
311
- safe: false,
312
- reason: 'Update manifest is missing a SHA-256 checksum',
313
- };
314
- }
315
-
316
- const assetName = String(asset.name || '');
317
- const entry = assets.find(item => String(item.file || item.name || basenameFromUrl(item.url || item.tarUrl || item.downloadUrl) || '') === assetName) || (assets.length === 0 ? asset : null);
318
- if (!entry) {
319
- return {
320
- safe: false,
321
- reason: 'Update manifest does not describe the app bundle',
322
- };
323
- }
324
- if (entry.type && entry.type !== 'app-bundle') {
325
- return {
326
- safe: false,
327
- reason: 'Update manifest does not mark the app bundle correctly',
328
- };
329
- }
330
- if (!assetMatchesRuntime(entry, runtime)) {
331
- return {
332
- safe: false,
333
- reason: `Update app bundle is not compatible with ${runtime.platform}-${runtime.arch}`,
334
- };
335
- }
336
- const checksumUrl = entry.checksum_url || entry.checksumUrl || asset.checksum_url || asset.checksumUrl || '';
337
- if (!normalizeSha256(entry.sha256 || asset.sha256) && !checksumUrl) {
338
- return {
339
- safe: false,
340
- reason: 'Update manifest app bundle is missing a SHA-256 checksum',
341
- };
342
- }
343
- return { safe: true, reason: '' };
344
- }
345
-
346
91
  function requestWithRedirects(url, options = {}, redirectCount = 0, authOrigin = null) {
347
92
  if (redirectCount > 5) {
348
93
  return Promise.reject(new Error(`too many redirects for ${url}`));
@@ -414,274 +159,6 @@ async function requestJson(url, options = {}) {
414
159
  return JSON.parse(Buffer.concat(chunks).toString('utf8'));
415
160
  }
416
161
 
417
- async function requestText(url, options = {}) {
418
- const response = await requestWithRedirects(url, options);
419
- const chunks = [];
420
- for await (const chunk of response) {
421
- chunks.push(chunk);
422
- }
423
- return Buffer.concat(chunks).toString('utf8');
424
- }
425
-
426
- function decodeHtmlAttribute(value) {
427
- return String(value || '')
428
- .replace(/&/g, '&')
429
- .replace(/"/g, '"')
430
- .replace(/'/g, "'")
431
- .replace(/&lt;/g, '<')
432
- .replace(/&gt;/g, '>');
433
- }
434
-
435
- function isDirectoryUpdateSource(value) {
436
- const raw = String(value || '').trim();
437
- if (!raw) return false;
438
- try {
439
- return new URL(raw).pathname.endsWith('/');
440
- } catch {
441
- return raw.endsWith('/');
442
- }
443
- }
444
-
445
- function isGitHubReleasePage(value) {
446
- try {
447
- const url = new URL(value);
448
- return url.hostname === 'github.com' && /\/releases\/(?:latest|tag\/[^/]+)\/?$/i.test(url.pathname);
449
- } catch {
450
- return false;
451
- }
452
- }
453
-
454
- function githubReleaseTagFromPage(body) {
455
- for (const match of String(body || '').matchAll(/\/releases\/tag\/([^"'/?#<]+)/gi)) {
456
- const tag = decodeHtmlAttribute(match[1]);
457
- if (/^v\d/.test(tag)) return tag;
458
- }
459
- return '';
460
- }
461
-
462
- function githubExpandedAssetsUrl(pageUrl, tag) {
463
- try {
464
- const url = new URL(pageUrl);
465
- const parts = url.pathname.split('/').filter(Boolean);
466
- if (parts.length < 2 || !tag) return '';
467
- return `${url.origin}/${parts[0]}/${parts[1]}/releases/expanded_assets/${encodeURIComponent(tag)}`;
468
- } catch {
469
- return '';
470
- }
471
- }
472
-
473
- function releaseFromGitHubReleasePage(body, options = {}) {
474
- const pageUrl = options.pageUrl || '';
475
- const entries = [];
476
- for (const match of String(body || '').matchAll(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)) {
477
- const value = decodeHtmlAttribute(match[1] || match[2] || match[3]).trim();
478
- if (value) entries.push(value);
479
- }
480
- const checksumUrl = entries
481
- .map(entry => ({ entry, file: basenameFromUrl(entry) }))
482
- .find(({ file }) => /(?:checksums?|sha256)\.(?:txt|sha256)$/i.test(file))?.entry || '';
483
- const assets = entries
484
- .map(entry => {
485
- const file = basenameFromUrl(entry);
486
- const runtime = runtimeFromBundleName(file);
487
- if (!runtime || !/^farming[-_].*\.tar\.gz$/i.test(file)) return null;
488
- const browser_download_url = resolveUpdateUrl(entry, pageUrl);
489
- if (!browser_download_url) return null;
490
- return {
491
- type: 'app-bundle',
492
- name: file,
493
- file,
494
- releaseVersion: normalizeVersion(file),
495
- browser_download_url,
496
- checksum_url: resolveUpdateUrl(checksumUrl, pageUrl),
497
- ...runtime,
498
- };
499
- })
500
- .filter(Boolean);
501
- const latestVersion = assets[0]?.releaseVersion || '';
502
- return {
503
- __directAssets: true,
504
- tag_name: latestVersion ? `v${latestVersion}` : '',
505
- name: latestVersion ? `v${latestVersion}` : '',
506
- published_at: '',
507
- assets,
508
- };
509
- }
510
-
511
- function releaseFromDirectoryListing(body, options = {}) {
512
- const directoryUrl = options.directoryUrl || '';
513
- const assetBaseUrl = options.assetBaseUrl || directoryUrl;
514
- const entries = [];
515
- const seen = new Set();
516
- const addCandidate = (value) => {
517
- const raw = decodeHtmlAttribute(value).trim();
518
- if (!raw || seen.has(raw)) return;
519
- seen.add(raw);
520
- entries.push(raw);
521
- };
522
-
523
- for (const match of String(body || '').matchAll(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)) {
524
- addCandidate(match[1] || match[2] || match[3]);
525
- }
526
- for (const match of String(body || '').matchAll(/\bfarming[-_][^\s"'<>]+?\.tar\.gz(?![\w.])/gi)) {
527
- addCandidate(match[0]);
528
- }
529
-
530
- const checksumUrls = new Map();
531
- entries.forEach(entry => {
532
- const file = basenameFromUrl(entry);
533
- const match = /^(farming[-_].*\.tar\.gz)\.sha256$/i.exec(file);
534
- if (!match) return;
535
- const url = resolveUpdateUrl(entry, assetBaseUrl) || resolveUpdateUrl(file, assetBaseUrl);
536
- if (url) checksumUrls.set(match[1], url);
537
- });
538
-
539
- const assets = entries
540
- .map(entry => {
541
- const file = basenameFromUrl(entry);
542
- if (!/^farming[-_].*\.tar\.gz$/i.test(file)) return null;
543
- if (/(sha256|checksum|checksums)/i.test(file)) return null;
544
- const url = resolveUpdateUrl(entry, assetBaseUrl) || resolveUpdateUrl(file, assetBaseUrl);
545
- if (!url) return null;
546
- return {
547
- type: 'app-bundle',
548
- file,
549
- name: file,
550
- releaseVersion: normalizeVersion(file),
551
- browser_download_url: url,
552
- checksum_url: checksumUrls.get(file) || '',
553
- size: 0,
554
- };
555
- })
556
- .filter(Boolean)
557
- .sort((left, right) => (
558
- compareVersions(right.releaseVersion, left.releaseVersion) ||
559
- String(right.name).localeCompare(String(left.name))
560
- ));
561
- const latestVersion = assets[0] ? assets[0].releaseVersion : '';
562
- return {
563
- __manifest: {
564
- releaseVersion: latestVersion,
565
- assets: assets.map(asset => ({
566
- type: asset.type,
567
- file: asset.file,
568
- url: asset.browser_download_url,
569
- checksum_url: asset.checksum_url,
570
- releaseVersion: asset.releaseVersion,
571
- })),
572
- },
573
- tag_name: latestVersion ? `v${latestVersion}` : '',
574
- name: latestVersion ? `v${latestVersion}` : '',
575
- published_at: '',
576
- assets,
577
- };
578
- }
579
-
580
- async function downloadFile(url, outputPath, options = {}) {
581
- const response = await requestWithRedirects(url, {
582
- ...options,
583
- accept: 'application/octet-stream',
584
- });
585
- const responseLength = Number(response.headers['content-length']);
586
- const expectedLength = Number(options.totalBytes);
587
- const totalBytes = Number.isFinite(responseLength) && responseLength > 0
588
- ? responseLength
589
- : (Number.isFinite(expectedLength) && expectedLength > 0 ? expectedLength : 0);
590
- let receivedBytes = 0;
591
- const trackProgress = new Transform({
592
- transform(chunk, _encoding, callback) {
593
- receivedBytes += chunk.length;
594
- try {
595
- if (typeof options.onProgress === 'function') {
596
- options.onProgress({ receivedBytes, totalBytes });
597
- }
598
- callback(null, chunk);
599
- } catch (error) {
600
- callback(error);
601
- }
602
- },
603
- });
604
- await pipeline(response, trackProgress, fs.createWriteStream(outputPath));
605
- }
606
-
607
- function sha256File(filePath) {
608
- const hash = crypto.createHash('sha256');
609
- hash.update(fs.readFileSync(filePath));
610
- return hash.digest('hex');
611
- }
612
-
613
- function sha256FromChecksumText(text, assetName) {
614
- const escapedName = String(assetName || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
615
- const match = new RegExp(`^\\s*([a-f0-9]{64})\\s+(?:\\*?${escapedName})\\s*$`, 'im').exec(String(text || ''));
616
- return normalizeSha256(match && match[1]);
617
- }
618
-
619
- function validateArchiveEntries(entries) {
620
- const roots = new Set();
621
- for (const rawEntry of Array.isArray(entries) ? entries : []) {
622
- const entry = String(rawEntry || '').replace(/\\/g, '/');
623
- if (!entry || entry.startsWith('/') || entry.includes('\0')) {
624
- throw new Error(`downloaded release contains an unsafe archive path: ${rawEntry}`);
625
- }
626
- const parts = entry.split('/').filter(Boolean);
627
- if (parts.some(part => part === '..')) {
628
- throw new Error(`downloaded release contains path traversal: ${rawEntry}`);
629
- }
630
- if (parts[0]) roots.add(parts[0]);
631
- }
632
- if (roots.size !== 1) {
633
- throw new Error(`downloaded release must contain exactly one top-level directory, found ${roots.size}`);
634
- }
635
- }
636
-
637
- function listTarArchiveEntries(archivePath) {
638
- return new Promise((resolve, reject) => {
639
- childProcess.execFile('tar', ['-tzf', archivePath], { maxBuffer: 20 * 1024 * 1024 }, (error, stdout) => {
640
- if (error) {
641
- reject(new Error(`failed to inspect downloaded release archive: ${error.message || error}`));
642
- return;
643
- }
644
- resolve(String(stdout || '').split(/\r?\n/).map(line => line.trim()).filter(Boolean));
645
- });
646
- });
647
- }
648
-
649
- function validateExtractedSymlinks(releaseDir) {
650
- const releaseRoot = path.resolve(releaseDir);
651
- const visit = directory => {
652
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
653
- const entryPath = path.join(directory, entry.name);
654
- if (entry.isSymbolicLink()) {
655
- const target = fs.readlinkSync(entryPath);
656
- const resolvedTarget = path.resolve(path.dirname(entryPath), target);
657
- if (path.isAbsolute(target) || (resolvedTarget !== releaseRoot && !resolvedTarget.startsWith(`${releaseRoot}${path.sep}`))) {
658
- throw new Error(`downloaded release contains a symlink outside the bundle: ${entryPath}`);
659
- }
660
- continue;
661
- }
662
- if (entry.isDirectory()) visit(entryPath);
663
- }
664
- };
665
- visit(releaseRoot);
666
- }
667
-
668
- function findReleaseDirectory(rootDir) {
669
- const entries = fs.readdirSync(rootDir, { withFileTypes: true });
670
- const directory = entries.find(entry => entry.isDirectory());
671
- if (!directory) {
672
- throw new Error('downloaded release archive did not contain a directory');
673
- }
674
- return path.join(rootDir, directory.name);
675
- }
676
-
677
- function releaseInstallDir(rootDir, env = process.env) {
678
- if (env.FARMING_INSTALL_DIR) return env.FARMING_INSTALL_DIR;
679
- if (fs.existsSync(path.join(rootDir, '.farming.pid')) || fs.existsSync(path.join(rootDir, 'RELEASE.json'))) {
680
- return rootDir;
681
- }
682
- return path.join(os.homedir(), 'farming');
683
- }
684
-
685
162
  function nodeScriptInvocation(nodePath, scriptPath, env = process.env) {
686
163
  if (env.FARMING_NODE_LD && env.FARMING_NODE_LIBRARY_PATH) {
687
164
  return {
@@ -761,11 +238,6 @@ function npmVersionsFromMetadata(metadata, currentVersion) {
761
238
  class FarmingUpdateService {
762
239
  constructor(options = {}) {
763
240
  this.rootDir = options.rootDir || path.join(__dirname, '..');
764
- this.getUpdateUrl = typeof options.getUpdateUrl === 'function' ? options.getUpdateUrl : null;
765
- this.manifestUrl = options.updateUrl || options.manifestUrl || '';
766
- this.assetBaseUrl = options.assetBaseUrl || '';
767
- this.assetPattern = options.assetPattern || '';
768
- this.authToken = options.authToken || '';
769
241
  this.installMethod = options.installMethod || detectInstallMethod(this.rootDir, {
770
242
  packagedRuntime: options.packagedRuntime === true,
771
243
  });
@@ -782,14 +254,10 @@ class FarmingUpdateService {
782
254
  this.configDir = options.configDir || path.join(os.homedir(), '.farming');
783
255
  this.now = options.now || (() => Date.now());
784
256
  this.fetchJson = options.fetchJson || requestJson;
785
- this.fetchText = options.fetchText || requestText;
786
- this.downloadFile = options.downloadFile || downloadFile;
787
- this.listArchiveEntries = options.listArchiveEntries || listTarArchiveEntries;
788
257
  this.execFile = options.execFile || childProcess.execFile;
789
258
  this.getNpmGlobalRoot = options.getNpmGlobalRoot
790
259
  || ((npmCommand, npmPrefix) => readNpmGlobalRoot(npmCommand, npmPrefix, this.execFile));
791
260
  this.spawn = options.spawn || childProcess.spawn;
792
- this.latestCache = null;
793
261
  this.npmCache = null;
794
262
  this.installState = { phase: 'idle' };
795
263
  this.installStartPromise = null;
@@ -798,11 +266,6 @@ class FarmingUpdateService {
798
266
  this.updateStagingDir = options.updateStagingDir || storageLayout.updateStagingDir(this.configDir);
799
267
  }
800
268
 
801
- updateUrl() {
802
- const configured = this.getUpdateUrl ? this.getUpdateUrl() : this.manifestUrl;
803
- return String(configured || '').trim();
804
- }
805
-
806
269
  currentVersion() {
807
270
  const release = readJsonFile(path.join(this.rootDir, 'RELEASE.json')) || {};
808
271
  const pkg = readJsonFile(path.join(this.rootDir, 'package.json')) || {};
@@ -815,7 +278,7 @@ class FarmingUpdateService {
815
278
  compatibilityProfile: String(release.compatibilityProfile || ''),
816
279
  bundledGlibcRuntime: release.bundledGlibcRuntime === true,
817
280
  type: this.installMethod,
818
- installDir: this.installMethod === 'npm' ? this.rootDir : releaseInstallDir(this.rootDir),
281
+ installDir: this.rootDir,
819
282
  };
820
283
  }
821
284
 
@@ -962,157 +425,9 @@ class FarmingUpdateService {
962
425
  };
963
426
  }
964
427
 
965
- async latestRelease(options = {}) {
966
- const updateUrl = this.updateUrl();
967
- if (!updateUrl) return null;
968
- if (!options.force && this.latestCache && this.latestCache.source === updateUrl && this.now() - this.latestCache.checkedAt < CACHE_TTL_MS) {
969
- return this.latestCache.release;
970
- }
971
- let release;
972
- if (isGitHubReleasePage(updateUrl)) {
973
- const pageBody = await this.fetchText(updateUrl, {
974
- accept: 'text/html,application/xhtml+xml',
975
- authToken: this.authToken,
976
- });
977
- const tag = githubReleaseTagFromPage(pageBody);
978
- const expandedAssetsUrl = githubExpandedAssetsUrl(updateUrl, tag);
979
- if (!expandedAssetsUrl) throw new Error('GitHub Release page did not expose a release tag');
980
- release = releaseFromGitHubReleasePage(await this.fetchText(expandedAssetsUrl, {
981
- accept: 'text/html,application/xhtml+xml',
982
- authToken: this.authToken,
983
- }), { pageUrl: expandedAssetsUrl });
984
- } else if (isDirectoryUpdateSource(updateUrl)) {
985
- release = releaseFromDirectoryListing(await this.fetchText(updateUrl, {
986
- accept: 'text/html, text/plain',
987
- authToken: this.authToken,
988
- }), {
989
- directoryUrl: updateUrl,
990
- assetBaseUrl: this.assetBaseUrl,
991
- });
992
- } else {
993
- const payload = await this.fetchJson(updateUrl, {
994
- accept: 'application/json',
995
- authToken: this.authToken,
996
- });
997
- release = Array.isArray(payload && payload.assets) && payload.assets.some(asset => asset && asset.browser_download_url)
998
- ? releaseFromAssetListing(payload)
999
- : releaseFromManifest(payload, {
1000
- manifestUrl: updateUrl,
1001
- assetBaseUrl: this.assetBaseUrl,
1002
- });
1003
- }
1004
- this.latestCache = {
1005
- checkedAt: this.now(),
1006
- source: updateUrl,
1007
- release,
1008
- };
1009
- return release;
1010
- }
1011
-
1012
- async latestManifest(release) {
1013
- if (release && release.__directAssets) return null;
1014
- if (release && release.__manifest) return release.__manifest;
1015
- const asset = selectManifestAsset(release);
1016
- if (!asset) return null;
1017
- try {
1018
- return await this.fetchJson(asset.browser_download_url, {
1019
- authToken: this.authToken,
1020
- });
1021
- } catch {
1022
- return null;
1023
- }
1024
- }
1025
-
1026
- versionOptionsFromRelease(release, manifest = null) {
1027
- const current = this.currentVersion();
1028
- const updateUrl = this.updateUrl();
1029
- const comparableCurrentVersion = normalizeVersion(current.releaseVersion || current.packageVersion);
1030
- const latestVersion = releaseVersionFromRelease(release);
1031
- const configured = Boolean(updateUrl);
1032
- return selectableReleaseAssets(release, this.assetPattern, this.runtime, current.compatibilityProfile).map(asset => {
1033
- const version = releaseAssetVersion(asset, latestVersion);
1034
- const safety = configured
1035
- ? manifestAssetSafety(asset, manifest, { runtime: this.runtime })
1036
- : { safe: false, reason: UPDATE_SOURCE_UNCONFIGURED_REASON };
1037
- const newer = Boolean(version && compareVersions(version, comparableCurrentVersion) > 0);
1038
- return {
1039
- version,
1040
- assetName: asset.name || '',
1041
- assetSize: asset.size || 0,
1042
- blockedReason: safety.reason,
1043
- installable: Boolean(safety.safe),
1044
- available: Boolean(newer && safety.safe),
1045
- };
1046
- });
1047
- }
1048
-
1049
- statusFromRelease(release, manifest = null, options = {}) {
1050
- const current = this.currentVersion();
1051
- const updateUrl = this.updateUrl();
1052
- const latestVersion = releaseVersionFromRelease(release);
1053
- const comparableCurrentVersion = normalizeVersion(current.releaseVersion || current.packageVersion);
1054
- const latestAsset = selectableReleaseAssets(release, this.assetPattern, this.runtime, current.compatibilityProfile)[0] || null;
1055
- const asset = selectReleaseAssetByName(release, options.assetName, this.assetPattern, this.runtime, current.compatibilityProfile);
1056
- const configured = Boolean(updateUrl);
1057
- const safety = configured
1058
- ? manifestAssetSafety(asset, manifest, { runtime: this.runtime })
1059
- : { safe: false, reason: UPDATE_SOURCE_UNCONFIGURED_REASON };
1060
- const selectedVersion = releaseAssetVersion(asset, latestVersion);
1061
- const newer = Boolean(asset && selectedVersion && compareVersions(selectedVersion, comparableCurrentVersion) > 0);
1062
- const available = Boolean(newer && safety.safe);
1063
- const versions = this.versionOptionsFromRelease(release, manifest);
1064
- const noCompatibleBundleReason = this.runtime
1065
- ? `Update source has no compatible app bundle for ${this.runtime.platform}-${this.runtime.arch}`
1066
- : 'Update source has no app bundle asset';
1067
-
1068
- return {
1069
- method: this.installMethod,
1070
- current,
1071
- latest: {
1072
- version: latestVersion,
1073
- tag: release && release.tag_name ? release.tag_name : '',
1074
- name: release && release.name ? release.name : '',
1075
- publishedAt: release && release.published_at ? release.published_at : '',
1076
- assetName: latestAsset ? latestAsset.name : '',
1077
- assetSize: latestAsset ? latestAsset.size || 0 : 0,
1078
- blockedReason: versions[0] ? versions[0].blockedReason : (this.runtime ? noCompatibleBundleReason : (safety.reason || noCompatibleBundleReason)),
1079
- source: updateUrl || '',
1080
- },
1081
- selected: {
1082
- version: selectedVersion,
1083
- assetName: asset ? asset.name : '',
1084
- assetSize: asset ? asset.size || 0 : 0,
1085
- blockedReason: safety.reason,
1086
- },
1087
- versions,
1088
- runtime: this.runtime,
1089
- available,
1090
- installable: Boolean(asset && safety.safe),
1091
- checkedAt: new Date(this.now()).toISOString(),
1092
- state: this.currentInstallState(),
1093
- };
1094
- }
1095
-
1096
428
  async check(options = {}) {
1097
429
  if (this.installMethod === 'npm') return this.npmStatus(options);
1098
- if (!installMethodAllowsBundleUpdate(this.installMethod)) return this.unsupportedStatus();
1099
- if (!this.updateUrl()) return this.statusFromRelease(null, null, options);
1100
- const release = await this.latestRelease(options);
1101
- const manifest = await this.latestManifest(release);
1102
- return this.statusFromRelease(release, manifest, options);
1103
- }
1104
-
1105
- installEnvironment() {
1106
- const current = this.currentVersion();
1107
- return {
1108
- ...process.env,
1109
- FARMING_INSTALL_DIR: current.installDir,
1110
- FARMING_PORT: process.env.FARMING_PORT || process.env.PORT || '6694',
1111
- FARMING_BASE_PATH: process.env.FARMING_BASE_PATH || '/farming',
1112
- FARMING_CONFIG_DIR: process.env.FARMING_CONFIG_DIR || this.configDir,
1113
- ...(process.env.FARMING_SERVER_HOME ? { FARMING_SERVER_HOME: process.env.FARMING_SERVER_HOME } : {}),
1114
- ...(process.env.FARMING_DISABLE_AUTH ? { FARMING_DISABLE_AUTH: process.env.FARMING_DISABLE_AUTH } : {}),
1115
- };
430
+ return this.unsupportedStatus();
1116
431
  }
1117
432
 
1118
433
  async startInstall(options = {}) {
@@ -1134,52 +449,7 @@ class FarmingUpdateService {
1134
449
  if (currentState.phase === 'ready-to-restart') return currentState;
1135
450
 
1136
451
  if (this.installMethod === 'npm') return this.startNpmInstall(options);
1137
- if (!installMethodAllowsBundleUpdate(this.installMethod)) {
1138
- throw new Error(installMethodBlockedReason(this.installMethod));
1139
- }
1140
-
1141
- const release = await this.latestRelease({ force: true });
1142
- const manifest = await this.latestManifest(release);
1143
- const status = this.statusFromRelease(release, manifest, options);
1144
- if (!status.available) {
1145
- const error = status.installable
1146
- ? 'Farming is already up to date'
1147
- : (status.latest.blockedReason || 'Update source has no app bundle asset');
1148
- this.installState = {
1149
- phase: 'failed',
1150
- error,
1151
- checkedAt: status.checkedAt,
1152
- };
1153
- return this.installState;
1154
- }
1155
-
1156
- const asset = selectReleaseAssetByName(
1157
- release,
1158
- options.assetName,
1159
- this.assetPattern,
1160
- this.runtime,
1161
- this.currentVersion().compatibilityProfile,
1162
- );
1163
- this.persistInstallState({
1164
- phase: 'downloading',
1165
- method: this.installMethod,
1166
- version: status.selected.version,
1167
- previousVersion: status.current.releaseVersion || status.current.packageVersion,
1168
- assetName: status.selected.assetName,
1169
- receivedBytes: 0,
1170
- totalBytes: Number(status.selected.assetSize) || 0,
1171
- startedAt: new Date(this.now()).toISOString(),
1172
- logPath: path.join(this.configDir, 'farming-update.log'),
1173
- });
1174
- void this.runInstall(asset).catch(error => {
1175
- this.persistInstallState({
1176
- ...this.installState,
1177
- phase: 'failed',
1178
- error: error.message || String(error),
1179
- completedAt: new Date(this.now()).toISOString(),
1180
- });
1181
- });
1182
- return this.installState;
452
+ throw new Error(installMethodBlockedReason(this.installMethod));
1183
453
  }
1184
454
 
1185
455
  async startNpmInstall(options = {}) {
@@ -1287,6 +557,9 @@ class FarmingUpdateService {
1287
557
  }
1288
558
 
1289
559
  async applyPreparedUpdateUnreserved() {
560
+ if (this.installMethod !== 'npm') {
561
+ throw new Error(installMethodBlockedReason(this.installMethod));
562
+ }
1290
563
  const prepared = this.currentInstallState();
1291
564
  if (prepared.phase !== 'ready-to-restart') {
1292
565
  throw new Error('No prepared Farming update is ready to restart');
@@ -1300,93 +573,57 @@ class FarmingUpdateService {
1300
573
  }
1301
574
 
1302
575
  const nodePath = process.env.FARMING_NODE_BIN || process.execPath;
1303
- let helperPath;
1304
- let payload;
1305
- let env;
1306
- if (this.installMethod === 'npm') {
1307
- const target = await this.npmUpdateTarget();
1308
- if (!target.proven) throw new Error(target.error);
1309
- if (!path.isAbsolute(String(prepared.stagingPrefix || '')) || !path.isAbsolute(String(prepared.stagingPackageRoot || ''))) {
1310
- throw new Error('Prepared npm update is missing its staging identity');
1311
- }
1312
- const stagingPrefix = normalizePathForCompare(prepared.stagingPrefix);
1313
- if (!pathIsInside(normalizePathForCompare(this.updateStagingDir), stagingPrefix)) {
1314
- throw new Error('Prepared npm update is outside the Farming staging directory');
1315
- }
1316
- if (path.resolve(prepared.stagingPackageRoot) !== path.resolve(npmPackageRoot(
1317
- path.join(prepared.stagingPrefix, 'lib', 'node_modules'),
1318
- this.npmPackageName,
1319
- ))) {
1320
- throw new Error('Prepared npm update has an invalid package root');
1321
- }
1322
- const stagingPackageRoot = normalizePathForCompare(prepared.stagingPackageRoot);
1323
- const stagedMetadata = readJsonFile(path.join(stagingPackageRoot, 'package.json')) || {};
1324
- if (normalizeVersion(stagedMetadata.version) !== normalizeVersion(prepared.version)) {
1325
- throw new Error('Prepared npm update is no longer available; prepare it again');
1326
- }
1327
- helperPath = path.join(__dirname, 'npm-update-helper.js');
1328
- payload = {
1329
- action: 'apply',
1330
- packageName: this.npmPackageName,
1331
- targetVersion: prepared.version,
1332
- previousVersion: prepared.previousVersion,
1333
- startedAt: prepared.startedAt,
1334
- preparedAt: prepared.preparedAt,
1335
- stateFile: this.updateStateFile,
1336
- logPath: prepared.logPath || this.updateLogFile,
1337
- cliPath: path.join(this.rootDir, 'bin', 'farming'),
1338
- packageRoot: target.packageRoot,
1339
- nodePath,
1340
- npmCommand: process.env.FARMING_NPM_COMMAND || 'npm',
1341
- npmPrefix: target.npmPrefix,
1342
- npmFallbackRegistryUrl: this.npmRegistryUrl,
1343
- stagingPrefix,
1344
- stagingPackageRoot,
1345
- serverPid: process.pid,
1346
- configDir: this.configDir,
1347
- port: process.env.FARMING_PORT || process.env.PORT || '6694',
1348
- basePath: process.env.FARMING_BASE_PATH || '/farming',
1349
- serverHome: process.env.FARMING_SERVER_HOME || '',
1350
- disableAuth: /^(1|true|yes|on)$/i.test(String(process.env.FARMING_DISABLE_AUTH || '')),
1351
- };
1352
- env = { ...process.env, FARMING_NPM_UPDATE_PAYLOAD: JSON.stringify(payload) };
1353
- } else {
1354
- if (!installMethodAllowsBundleUpdate(this.installMethod)) {
1355
- throw new Error(installMethodBlockedReason(this.installMethod));
1356
- }
1357
- if (!path.isAbsolute(String(prepared.releaseDir || '')) || !path.isAbsolute(String(prepared.installer || '')) || !fs.existsSync(prepared.installer)) {
1358
- throw new Error('Prepared bundle update is no longer available; prepare it again');
1359
- }
1360
- const releaseDir = normalizePathForCompare(prepared.releaseDir);
1361
- const installer = normalizePathForCompare(prepared.installer);
1362
- if (!pathIsInside(normalizePathForCompare(os.tmpdir()), releaseDir)
1363
- || !path.basename(path.dirname(releaseDir)).startsWith('farming-update.')
1364
- || installer !== normalizePathForCompare(path.join(releaseDir, 'scripts', 'install-release.sh'))) {
1365
- throw new Error('Prepared bundle update has an invalid staging identity');
1366
- }
1367
- const releaseMetadata = readJsonFile(path.join(releaseDir, 'RELEASE.json')) || {};
1368
- const preparedVersion = normalizeVersion(releaseMetadata.releaseVersion || releaseMetadata.packageVersion);
1369
- if (preparedVersion && preparedVersion !== normalizeVersion(prepared.version)) {
1370
- throw new Error('Prepared bundle version does not match the selected update');
1371
- }
1372
- if (!assetMatchesRuntime(releaseMetadata, this.runtime)) {
1373
- throw new Error(`Prepared bundle is not compatible with ${this.runtime.platform}-${this.runtime.arch}`);
1374
- }
1375
- helperPath = path.join(__dirname, 'bundle-update-helper.js');
1376
- payload = {
1377
- method: this.installMethod,
1378
- targetMethod: prepared.targetMethod,
1379
- version: prepared.version,
1380
- previousVersion: prepared.previousVersion,
1381
- startedAt: prepared.startedAt,
1382
- preparedAt: prepared.preparedAt,
1383
- stateFile: this.updateStateFile,
1384
- logPath: prepared.logPath || this.updateLogFile,
1385
- releaseDir,
1386
- installer,
1387
- };
1388
- env = { ...this.installEnvironment(), FARMING_BUNDLE_UPDATE_PAYLOAD: JSON.stringify(payload) };
576
+ const serverProcessIdentity = await readServerProcessIdentity(process.pid);
577
+ if (!serverProcessIdentity) {
578
+ throw new Error('Running Farming server process identity could not be verified');
579
+ }
580
+ const target = await this.npmUpdateTarget();
581
+ if (!target.proven) throw new Error(target.error);
582
+ if (!path.isAbsolute(String(prepared.stagingPrefix || '')) || !path.isAbsolute(String(prepared.stagingPackageRoot || ''))) {
583
+ throw new Error('Prepared npm update is missing its staging identity');
584
+ }
585
+ const stagingPrefix = normalizePathForCompare(prepared.stagingPrefix);
586
+ if (!pathIsInside(normalizePathForCompare(this.updateStagingDir), stagingPrefix)) {
587
+ throw new Error('Prepared npm update is outside the Farming staging directory');
1389
588
  }
589
+ if (path.resolve(prepared.stagingPackageRoot) !== path.resolve(npmPackageRoot(
590
+ path.join(prepared.stagingPrefix, 'lib', 'node_modules'),
591
+ this.npmPackageName,
592
+ ))) {
593
+ throw new Error('Prepared npm update has an invalid package root');
594
+ }
595
+ const stagingPackageRoot = normalizePathForCompare(prepared.stagingPackageRoot);
596
+ const stagedMetadata = readJsonFile(path.join(stagingPackageRoot, 'package.json')) || {};
597
+ if (normalizeVersion(stagedMetadata.version) !== normalizeVersion(prepared.version)) {
598
+ throw new Error('Prepared npm update is no longer available; prepare it again');
599
+ }
600
+ const helperPath = path.join(__dirname, 'npm-update-helper.js');
601
+ const payload = {
602
+ action: 'apply',
603
+ packageName: this.npmPackageName,
604
+ targetVersion: prepared.version,
605
+ previousVersion: prepared.previousVersion,
606
+ startedAt: prepared.startedAt,
607
+ preparedAt: prepared.preparedAt,
608
+ stateFile: this.updateStateFile,
609
+ logPath: prepared.logPath || this.updateLogFile,
610
+ cliPath: path.join(this.rootDir, 'bin', 'farming'),
611
+ packageRoot: target.packageRoot,
612
+ nodePath,
613
+ npmCommand: process.env.FARMING_NPM_COMMAND || 'npm',
614
+ npmPrefix: target.npmPrefix,
615
+ npmFallbackRegistryUrl: this.npmRegistryUrl,
616
+ stagingPrefix,
617
+ stagingPackageRoot,
618
+ serverPid: process.pid,
619
+ serverProcessIdentity,
620
+ configDir: this.configDir,
621
+ port: process.env.FARMING_PORT || process.env.PORT || '6694',
622
+ basePath: process.env.FARMING_BASE_PATH || '/farming',
623
+ serverHome: process.env.FARMING_SERVER_HOME || '',
624
+ disableAuth: /^(1|true|yes|on)$/i.test(String(process.env.FARMING_DISABLE_AUTH || '')),
625
+ };
626
+ const env = { ...process.env, FARMING_NPM_UPDATE_PAYLOAD: JSON.stringify(payload) };
1390
627
 
1391
628
  const state = this.persistInstallState({ ...prepared, phase: 'restarting', error: '' });
1392
629
  const helperInvocation = nodeScriptInvocation(nodePath, helperPath);
@@ -1413,107 +650,16 @@ class FarmingUpdateService {
1413
650
  return state;
1414
651
  }
1415
652
 
1416
- async runInstall(asset) {
1417
- if (!asset || !asset.browser_download_url) {
1418
- throw new Error('release asset is missing a download URL');
1419
- }
1420
-
1421
- fs.mkdirSync(this.configDir, { recursive: true });
1422
- const tempRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'farming-update.'));
1423
- const archivePath = path.join(tempRoot, asset.name || 'farming-update.tar.gz');
1424
- let lastProgressPercent = -1;
1425
- let lastProgressBytes = 0;
1426
- await this.downloadFile(asset.browser_download_url, archivePath, {
1427
- authToken: this.authToken,
1428
- totalBytes: Number(asset.size) || Number(this.installState.totalBytes) || 0,
1429
- onProgress: ({ receivedBytes, totalBytes }) => {
1430
- const safeReceivedBytes = Math.max(0, Number(receivedBytes) || 0);
1431
- const safeTotalBytes = Math.max(0, Number(totalBytes) || 0);
1432
- if (safeTotalBytes > 0) {
1433
- const percent = Math.min(100, Math.floor((safeReceivedBytes / safeTotalBytes) * 100));
1434
- if (percent === lastProgressPercent && safeReceivedBytes < safeTotalBytes) return;
1435
- lastProgressPercent = percent;
1436
- } else if (safeReceivedBytes - lastProgressBytes < 1024 * 1024) {
1437
- return;
1438
- }
1439
- lastProgressBytes = safeReceivedBytes;
1440
- this.persistInstallState({
1441
- ...this.installState,
1442
- receivedBytes: safeReceivedBytes,
1443
- totalBytes: safeTotalBytes,
1444
- });
1445
- },
1446
- });
1447
- let expectedSha256 = normalizeSha256(asset.sha256);
1448
- const checksumUrl = asset.checksum_url || asset.checksumUrl || '';
1449
- if (!expectedSha256 && checksumUrl) {
1450
- const checksumText = await this.fetchText(checksumUrl, {
1451
- accept: 'text/plain',
1452
- authToken: this.authToken,
1453
- });
1454
- expectedSha256 = sha256FromChecksumText(checksumText, asset.name);
1455
- }
1456
- if (!expectedSha256) {
1457
- throw new Error(`release asset is missing a valid SHA-256 checksum: ${asset.name || 'asset'}`);
1458
- }
1459
- const actualSha256 = sha256File(archivePath);
1460
- if (actualSha256 !== expectedSha256) {
1461
- throw new Error(`downloaded release checksum mismatch for ${asset.name || 'asset'}`);
1462
- }
1463
-
1464
- validateArchiveEntries(await this.listArchiveEntries(archivePath));
1465
-
1466
- this.persistInstallState({ ...this.installState, phase: 'extracting' });
1467
- await new Promise((resolve, reject) => {
1468
- this.execFile('tar', ['-xzf', archivePath, '-C', tempRoot], (error) => {
1469
- if (error) reject(error);
1470
- else resolve();
1471
- });
1472
- });
1473
-
1474
- const releaseDir = findReleaseDirectory(tempRoot);
1475
- validateExtractedSymlinks(releaseDir);
1476
- const releaseMetadata = readJsonFile(path.join(releaseDir, 'RELEASE.json')) || {};
1477
- if (!assetMatchesRuntime(releaseMetadata, this.runtime)) {
1478
- throw new Error(`downloaded release is not compatible with ${this.runtime.platform}-${this.runtime.arch}`);
1479
- }
1480
- const installer = path.join(releaseDir, 'scripts', 'install-release.sh');
1481
- if (!fs.existsSync(installer)) {
1482
- throw new Error('downloaded release is missing scripts/install-release.sh');
1483
- }
1484
- const logPath = this.installState.logPath || path.join(this.configDir, 'farming-update.log');
1485
- const targetMethod = String(releaseMetadata.updateMethod || releaseMetadata.type || this.installMethod);
1486
- this.persistInstallState({
1487
- ...this.installState,
1488
- phase: 'ready-to-restart',
1489
- targetMethod,
1490
- releaseDir,
1491
- installer,
1492
- logPath,
1493
- preparedAt: new Date(this.now()).toISOString(),
1494
- });
1495
- }
1496
653
  }
1497
654
 
1498
655
  module.exports = {
1499
656
  FarmingUpdateService,
1500
657
  compareVersions,
1501
658
  detectInstallMethod,
1502
- installMethodAllowsBundleUpdate,
1503
659
  normalizeVersion,
1504
660
  npmPackageMetadataUrl,
1505
661
  npmPrefixForPackageRoot,
1506
662
  npmPackageRoot,
1507
663
  npmVersionsFromMetadata,
1508
664
  readNpmGlobalRoot,
1509
- releaseInstallDir,
1510
- manifestAssetSafety,
1511
- normalizeSha256,
1512
- validateArchiveEntries,
1513
- releaseFromManifest,
1514
- releaseFromDirectoryListing,
1515
- releaseFromGitHubReleasePage,
1516
- releaseVersionFromManifest,
1517
- selectManifestAsset,
1518
- selectReleaseAsset,
1519
665
  };