@kirkchinese/harness-forge 0.0.0-stage → 0.5.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.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/assets/icon.svg +12 -0
- package/cordis.patch.yml +28 -0
- package/docs/DETAIL.zh.md +47 -0
- package/lib/agents/presets.d.ts +98 -0
- package/lib/agents/presets.js +292 -0
- package/lib/agents/profiles.d.ts +58 -0
- package/lib/agents/profiles.js +279 -0
- package/lib/agents/row.d.ts +17 -0
- package/lib/agents/row.js +148 -0
- package/lib/client/paths.d.ts +12 -0
- package/lib/client/paths.js +68 -0
- package/lib/client/styles.d.ts +8 -0
- package/lib/client/styles.js +89 -0
- package/lib/client/typert.d.ts +25 -0
- package/lib/client/typert.js +158 -0
- package/lib/client.js +23823 -0
- package/lib/commands/definition.d.ts +40 -0
- package/lib/commands/definition.js +113 -0
- package/lib/commands/output-styles.d.ts +42 -0
- package/lib/commands/output-styles.js +152 -0
- package/lib/commands/row.d.ts +9 -0
- package/lib/commands/row.js +157 -0
- package/lib/context/instructions.d.ts +32 -0
- package/lib/context/instructions.js +88 -0
- package/lib/context/row.d.ts +16 -0
- package/lib/context/row.js +17 -0
- package/lib/dsh/commands.d.ts +30 -0
- package/lib/dsh/commands.js +61 -0
- package/lib/dsh/host.d.ts +110 -0
- package/lib/dsh/host.js +217 -0
- package/lib/dsh/model-route.d.ts +21 -0
- package/lib/dsh/model-route.js +37 -0
- package/lib/dsh/session-records.d.ts +78 -0
- package/lib/dsh/session-records.js +36 -0
- package/lib/dsh/subagents.d.ts +46 -0
- package/lib/dsh/subagents.js +14 -0
- package/lib/forge/contract.d.ts +271 -0
- package/lib/forge/contract.js +45 -0
- package/lib/forge/follow.d.ts +30 -0
- package/lib/forge/follow.js +73 -0
- package/lib/forge/ledger.d.ts +206 -0
- package/lib/forge/ledger.js +1005 -0
- package/lib/forge/live-mounts.d.ts +45 -0
- package/lib/forge/live-mounts.js +78 -0
- package/lib/forge/npm.d.ts +31 -0
- package/lib/forge/npm.js +60 -0
- package/lib/forge/projects.d.ts +97 -0
- package/lib/forge/projects.js +343 -0
- package/lib/forge/receipts.d.ts +5 -0
- package/lib/forge/receipts.js +31 -0
- package/lib/forge/remote/archive.d.ts +65 -0
- package/lib/forge/remote/archive.js +565 -0
- package/lib/forge/remote/code-parts.d.ts +18 -0
- package/lib/forge/remote/code-parts.js +76 -0
- package/lib/forge/remote/fetch.d.ts +265 -0
- package/lib/forge/remote/fetch.js +1133 -0
- package/lib/forge/remote/service.d.ts +256 -0
- package/lib/forge/remote/service.js +868 -0
- package/lib/forge/row.d.ts +32 -0
- package/lib/forge/row.js +59 -0
- package/lib/forge/service.d.ts +115 -0
- package/lib/forge/service.js +290 -0
- package/lib/forge/settings.d.ts +43 -0
- package/lib/forge/settings.js +122 -0
- package/lib/forge/state.d.ts +129 -0
- package/lib/forge/state.js +266 -0
- package/lib/forge/trust.d.ts +48 -0
- package/lib/forge/trust.js +107 -0
- package/lib/forge/turns.d.ts +13 -0
- package/lib/forge/turns.js +56 -0
- package/lib/hooks/broker/engine.d.ts +112 -0
- package/lib/hooks/broker/engine.js +722 -0
- package/lib/hooks/broker/helpers.d.ts +10 -0
- package/lib/hooks/broker/helpers.js +22 -0
- package/lib/hooks/broker/lifecycle.d.ts +65 -0
- package/lib/hooks/broker/lifecycle.js +342 -0
- package/lib/hooks/broker/session-events.d.ts +27 -0
- package/lib/hooks/broker/session-events.js +205 -0
- package/lib/hooks/broker/tools.d.ts +52 -0
- package/lib/hooks/broker/tools.js +424 -0
- package/lib/hooks/broker/types.d.ts +264 -0
- package/lib/hooks/broker/types.js +1 -0
- package/lib/hooks/broker.d.ts +80 -0
- package/lib/hooks/broker.js +95 -0
- package/lib/hooks/codex-user.d.ts +5 -0
- package/lib/hooks/codex-user.js +109 -0
- package/lib/hooks/condition.d.ts +87 -0
- package/lib/hooks/condition.js +602 -0
- package/lib/hooks/config.d.ts +85 -0
- package/lib/hooks/config.js +154 -0
- package/lib/hooks/glob.d.ts +41 -0
- package/lib/hooks/glob.js +114 -0
- package/lib/hooks/matcher.d.ts +20 -0
- package/lib/hooks/matcher.js +39 -0
- package/lib/hooks/notice.d.ts +17 -0
- package/lib/hooks/notice.js +39 -0
- package/lib/hooks/output.d.ts +56 -0
- package/lib/hooks/output.js +214 -0
- package/lib/hooks/permissions.d.ts +19 -0
- package/lib/hooks/permissions.js +202 -0
- package/lib/hooks/powershell-aliases.d.ts +19 -0
- package/lib/hooks/powershell-aliases.js +58 -0
- package/lib/hooks/process.d.ts +64 -0
- package/lib/hooks/process.js +289 -0
- package/lib/hooks/row.d.ts +17 -0
- package/lib/hooks/row.js +96 -0
- package/lib/hooks/runner.d.ts +98 -0
- package/lib/hooks/runner.js +322 -0
- package/lib/hooks/shell-commands.d.ts +28 -0
- package/lib/hooks/shell-commands.js +241 -0
- package/lib/hooks/shell.d.ts +44 -0
- package/lib/hooks/shell.js +129 -0
- package/lib/hooks/transcript.d.ts +28 -0
- package/lib/hooks/transcript.js +141 -0
- package/lib/hooks/vocabulary.d.ts +57 -0
- package/lib/hooks/vocabulary.js +366 -0
- package/lib/index.d.ts +31 -0
- package/lib/index.js +287 -0
- package/lib/mcp/auth.d.ts +35 -0
- package/lib/mcp/auth.js +178 -0
- package/lib/mcp/catalog.d.ts +39 -0
- package/lib/mcp/catalog.js +69 -0
- package/lib/mcp/mount.d.ts +113 -0
- package/lib/mcp/mount.js +317 -0
- package/lib/mcp/policy.d.ts +42 -0
- package/lib/mcp/policy.js +43 -0
- package/lib/mcp/remote.d.ts +45 -0
- package/lib/mcp/remote.js +133 -0
- package/lib/mcp/row.d.ts +9 -0
- package/lib/mcp/row.js +225 -0
- package/lib/mods/bundler.d.ts +38 -0
- package/lib/mods/bundler.js +157 -0
- package/lib/mods/chain.d.ts +103 -0
- package/lib/mods/chain.js +436 -0
- package/lib/mods/claude.d.ts +27 -0
- package/lib/mods/claude.js +56 -0
- package/lib/mods/engine.d.ts +160 -0
- package/lib/mods/engine.js +701 -0
- package/lib/mods/expect.d.ts +8 -0
- package/lib/mods/expect.js +248 -0
- package/lib/mods/host.d.ts +105 -0
- package/lib/mods/host.js +462 -0
- package/lib/mods/loader.d.ts +53 -0
- package/lib/mods/loader.js +231 -0
- package/lib/mods/ops.d.ts +13 -0
- package/lib/mods/ops.js +117 -0
- package/lib/mods/row.d.ts +9 -0
- package/lib/mods/row.js +77 -0
- package/lib/mods/runtime.d.ts +60 -0
- package/lib/mods/runtime.js +133 -0
- package/lib/mods/service/commands.d.ts +17 -0
- package/lib/mods/service/commands.js +121 -0
- package/lib/mods/service/drawings.d.ts +36 -0
- package/lib/mods/service/drawings.js +64 -0
- package/lib/mods/service/sessions.d.ts +63 -0
- package/lib/mods/service/sessions.js +345 -0
- package/lib/mods/service/tools.d.ts +32 -0
- package/lib/mods/service/tools.js +253 -0
- package/lib/mods/service/turns.d.ts +33 -0
- package/lib/mods/service/turns.js +136 -0
- package/lib/mods/service/types.d.ts +151 -0
- package/lib/mods/service/types.js +1 -0
- package/lib/mods/service.d.ts +72 -0
- package/lib/mods/service.js +104 -0
- package/lib/mods/surfaces.d.ts +93 -0
- package/lib/mods/surfaces.js +309 -0
- package/lib/mods/values.d.ts +30 -0
- package/lib/mods/values.js +95 -0
- package/lib/opencode/bun.d.ts +40 -0
- package/lib/opencode/bun.js +168 -0
- package/lib/opencode/convert.d.ts +53 -0
- package/lib/opencode/convert.js +255 -0
- package/lib/opencode/row.d.ts +22 -0
- package/lib/opencode/row.js +104 -0
- package/lib/opencode/runtime/core.d.ts +74 -0
- package/lib/opencode/runtime/core.js +249 -0
- package/lib/opencode/runtime/events.d.ts +80 -0
- package/lib/opencode/runtime/events.js +281 -0
- package/lib/opencode/runtime/mount.d.ts +27 -0
- package/lib/opencode/runtime/mount.js +283 -0
- package/lib/opencode/runtime/server.d.ts +27 -0
- package/lib/opencode/runtime/server.js +354 -0
- package/lib/opencode/runtime/types.d.ts +109 -0
- package/lib/opencode/runtime/types.js +1 -0
- package/lib/opencode/runtime.d.ts +55 -0
- package/lib/opencode/runtime.js +79 -0
- package/lib/porting/adapter-paths.d.ts +13 -0
- package/lib/porting/adapter-paths.js +120 -0
- package/lib/porting/port-gap.d.ts +36 -0
- package/lib/porting/port-gap.js +158 -0
- package/lib/porting/port-sessions.d.ts +41 -0
- package/lib/porting/port-sessions.js +98 -0
- package/lib/porting/prompt.d.ts +23 -0
- package/lib/porting/prompt.js +51 -0
- package/lib/porting/row.d.ts +16 -0
- package/lib/porting/row.js +27 -0
- package/lib/porting/verify-port.d.ts +46 -0
- package/lib/porting/verify-port.js +82 -0
- package/lib/presets/fs-search.d.ts +25 -0
- package/lib/presets/fs-search.js +17 -0
- package/lib/presets/tool-filter.d.ts +35 -0
- package/lib/presets/tool-filter.js +91 -0
- package/lib/sessions/chat-import.d.ts +48 -0
- package/lib/sessions/chat-import.js +44 -0
- package/lib/sessions/claude.d.ts +35 -0
- package/lib/sessions/claude.js +104 -0
- package/lib/sessions/codex-discover.d.ts +34 -0
- package/lib/sessions/codex-discover.js +205 -0
- package/lib/sessions/codex-meta.d.ts +63 -0
- package/lib/sessions/codex-meta.js +148 -0
- package/lib/sessions/codex-text.d.ts +9 -0
- package/lib/sessions/codex-text.js +44 -0
- package/lib/sessions/codex.d.ts +42 -0
- package/lib/sessions/codex.js +270 -0
- package/lib/sessions/opencode.d.ts +38 -0
- package/lib/sessions/opencode.js +339 -0
- package/lib/sessions/persist.d.ts +162 -0
- package/lib/sessions/persist.js +377 -0
- package/lib/sessions/row.d.ts +15 -0
- package/lib/sessions/row.js +101 -0
- package/lib/sessions/turns.d.ts +31 -0
- package/lib/sessions/turns.js +63 -0
- package/lib/sessions/zstd.d.ts +15 -0
- package/lib/sessions/zstd.js +152 -0
- package/lib/shared/invocation.d.ts +169 -0
- package/lib/shared/invocation.js +325 -0
- package/lib/shared/render.d.ts +101 -0
- package/lib/shared/render.js +1353 -0
- package/lib/shared/util.d.ts +21 -0
- package/lib/shared/util.js +32 -0
- package/lib/skills/bundled.d.ts +3 -0
- package/lib/skills/bundled.js +42 -0
- package/lib/skills/provider.d.ts +74 -0
- package/lib/skills/provider.js +346 -0
- package/lib/skills/row.d.ts +22 -0
- package/lib/skills/row.js +204 -0
- package/lib/workbench/adapter-coverage.d.ts +65 -0
- package/lib/workbench/adapter-coverage.js +141 -0
- package/lib/workbench/model-tools.d.ts +10 -0
- package/lib/workbench/model-tools.js +122 -0
- package/lib/workbench/overview.d.ts +153 -0
- package/lib/workbench/overview.js +246 -0
- package/lib/workbench/remote.d.ts +161 -0
- package/lib/workbench/remote.js +561 -0
- package/lib/workbench/row.d.ts +15 -0
- package/lib/workbench/row.js +16 -0
- package/lib/workbench/settings.d.ts +19 -0
- package/lib/workbench/settings.js +60 -0
- package/lib/workbench/workbench.d.ts +130 -0
- package/lib/workbench/workbench.js +361 -0
- package/locale/agents/en.json +6 -0
- package/locale/agents/zh.json +6 -0
- package/locale/commands/en.json +6 -0
- package/locale/commands/zh.json +6 -0
- package/locale/context/en.json +6 -0
- package/locale/context/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/hooks/en.json +6 -0
- package/locale/hooks/zh.json +6 -0
- package/locale/mcp/en.json +6 -0
- package/locale/mcp/zh.json +6 -0
- package/locale/mods/en.json +6 -0
- package/locale/mods/zh.json +6 -0
- package/locale/opencode/en.json +6 -0
- package/locale/opencode/zh.json +6 -0
- package/locale/porter/en.json +6 -0
- package/locale/porter/zh.json +6 -0
- package/locale/sessions/en.json +6 -0
- package/locale/sessions/zh.json +6 -0
- package/locale/skills/en.json +6 -0
- package/locale/skills/zh.json +6 -0
- package/locale/workbench/en.json +6 -0
- package/locale/workbench/zh.json +6 -0
- package/locale/zh.json +7 -0
- package/package.json +247 -3
- package/runtime/opencode-host.mjs +270 -0
- package/skills/harness-forge/SKILL.md +47 -0
|
@@ -0,0 +1,1133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetching plugins from the network into Harness Forge's own data directory:
|
|
3
|
+
* git (a shallow, blobless, sparse fetch of one commit) when git is installed,
|
|
4
|
+
* else GitHub's `.tar.gz` over HTTPS; npm packages as their registry tarball
|
|
5
|
+
* alone; zip archives and hosted `marketplace.json` files over HTTPS.
|
|
6
|
+
*
|
|
7
|
+
* Nothing fetched runs before the person confirms it:
|
|
8
|
+
* - git runs isolated from this computer's git configuration (no system or
|
|
9
|
+
* global config, hooks, templates, credential helpers, fsmonitor, LFS
|
|
10
|
+
* filters or submodules), with only the transport of the URL allowed and
|
|
11
|
+
* every URL and ref after `--`. Private HTTPS repositories therefore need a
|
|
12
|
+
* URL git can read without a credential helper; a pasted `ssh` URL uses the
|
|
13
|
+
* person's own SSH setup.
|
|
14
|
+
* - npm does not run before confirmation: Harness Forge reads the package's
|
|
15
|
+
* registry document and downloads its tarball itself, at an exact version,
|
|
16
|
+
* from the registry's own origin, checked against its sha512 integrity.
|
|
17
|
+
* Once confirmed, the plugin and its registry dependencies are trusted, as
|
|
18
|
+
* OpenCode installs plugins: `npm install --ignore-scripts`, after refusing
|
|
19
|
+
* a resolved tree with anything that is not a registry tarball.
|
|
20
|
+
* - What a marketplace names may use HTTPS only and may not lead to this
|
|
21
|
+
* computer or its local network. Every HTTP request Harness Forge makes
|
|
22
|
+
* connects to the address it checked (no second resolution), and every
|
|
23
|
+
* redirect, also of what the person pasted, is checked again. git, for a
|
|
24
|
+
* marketplace's URL, is pinned to the addresses checked and follows no
|
|
25
|
+
* redirects; where it cannot be pinned (git older than 2.37, or a proxy
|
|
26
|
+
* resolving hosts for it), only GitHub is fetched, over its archive or
|
|
27
|
+
* through the proxy.
|
|
28
|
+
* - Every operation has a wall-clock bound, name resolution included, and
|
|
29
|
+
* downloads, unpacking and subprocesses a size bound enforced while they
|
|
30
|
+
* run (streamed bytes; written bytes; the size of the directory git or npm
|
|
31
|
+
* writes, polled).
|
|
32
|
+
*
|
|
33
|
+
* Behind a proxy (`HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY`, minus `NO_PROXY`,
|
|
34
|
+
* as git and npm read them) the proxy resolves hosts, so nothing can be
|
|
35
|
+
* pinned: Harness Forge then reaches only {@link PROXY_HOSTS}, the configured
|
|
36
|
+
* npm registry and the hosts the person pasted, through the proxy (CONNECT
|
|
37
|
+
* for https, an absolute URL for http), and git, for a marketplace, only those
|
|
38
|
+
* hosts as well.
|
|
39
|
+
* @module @kirkchinese/harness-forge
|
|
40
|
+
*/
|
|
41
|
+
import { execFile } from 'node:child_process';
|
|
42
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
43
|
+
import { lookup as dnsLookup } from 'node:dns/promises';
|
|
44
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
45
|
+
import { request as httpRequest } from 'node:http';
|
|
46
|
+
import { request as httpsRequest } from 'node:https';
|
|
47
|
+
import { BlockList, isIP } from 'node:net';
|
|
48
|
+
import { connect as tlsConnect } from 'node:tls';
|
|
49
|
+
import { homedir } from 'node:os';
|
|
50
|
+
import { join, relative, resolve } from 'node:path';
|
|
51
|
+
import { Readable } from 'node:stream';
|
|
52
|
+
import { dependencyProblem, githubCommitApi, githubTarball, gitTransport, HarnessError, isFullSha, isInside, isValidRef, normalizeRegistry, NPM_REGISTRY, } from '@kirkchinese/harness-forge-core';
|
|
53
|
+
import { messageOf } from '../../shared/util.js';
|
|
54
|
+
import { npmLaunch } from '../npm.js';
|
|
55
|
+
import { extractTarGz, extractZip, PLUGIN_LIMITS, refuseLinkedManifests, REPOSITORY_LIMITS, treeSize, zipRoot } from './archive.js';
|
|
56
|
+
/** What Harness Forge reaches through a proxy, besides the configured npm registry and the hosts the person pasted: GitHub and npm. */
|
|
57
|
+
export const PROXY_HOSTS = new Set(['github.com', 'codeload.github.com', 'api.github.com', 'raw.githubusercontent.com', 'objects.githubusercontent.com', 'registry.npmjs.org']);
|
|
58
|
+
/** Whether `NO_PROXY` exempts a host (`*`, a name and its subdomains, `.name`, optionally with `:port`). */
|
|
59
|
+
function noProxy(host, port) {
|
|
60
|
+
const list = (process.env['no_proxy'] ?? process.env['NO_PROXY'] ?? '').split(/[\s,]+/u).filter(entry => entry.length > 0);
|
|
61
|
+
const bare = host.toLowerCase().replace(/^\[|\]$/gu, '');
|
|
62
|
+
return list.some((entry) => {
|
|
63
|
+
if (entry === '*')
|
|
64
|
+
return true;
|
|
65
|
+
const match = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/u.exec(entry.toLowerCase());
|
|
66
|
+
if (match === null)
|
|
67
|
+
return false;
|
|
68
|
+
const name = match[1].replace(/^\[|\]$/gu, '').replace(/^\*?\./u, '');
|
|
69
|
+
if (match[2] !== undefined && match[2] !== port)
|
|
70
|
+
return false;
|
|
71
|
+
return bare === name || bare.endsWith(`.${name}`);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** The proxy git, npm and Harness Forge use for a URL, as they read the environment; undefined for a direct connection. */
|
|
75
|
+
export function proxyFor(url) {
|
|
76
|
+
// curl's order (lowercase first), which git and npm follow too.
|
|
77
|
+
const keys = url.protocol === 'https:' ? ['https_proxy', 'HTTPS_PROXY', 'all_proxy', 'ALL_PROXY'] : ['http_proxy', 'HTTP_PROXY', 'all_proxy', 'ALL_PROXY'];
|
|
78
|
+
const key = keys.find(name => (process.env[name]?.trim() ?? '').length > 0);
|
|
79
|
+
if (key === undefined)
|
|
80
|
+
return undefined;
|
|
81
|
+
const value = process.env[key].trim();
|
|
82
|
+
if (noProxy(url.hostname, url.port || (url.protocol === 'https:' ? '443' : '80')))
|
|
83
|
+
return undefined;
|
|
84
|
+
let proxy;
|
|
85
|
+
try {
|
|
86
|
+
proxy = new URL(/^[a-z][a-z0-9+.-]*:\/\//iu.test(value) ? value : `http://${value}`);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
// Its content is not repeated: it may hold a password.
|
|
90
|
+
throw new HarnessError('fetch-failed', `invalid proxy setting in ${key}`, { suggestion: `Set ${key} to a URL such as http://proxy.example:3128.` });
|
|
91
|
+
}
|
|
92
|
+
if (proxy.protocol !== 'http:' && proxy.protocol !== 'https:')
|
|
93
|
+
throw new HarnessError('fetch-failed', `Harness Forge supports http:// and https:// proxies, not ${proxy.protocol.replace(':', '')}://`, { suggestion: 'Set HTTPS_PROXY to an HTTP proxy.' });
|
|
94
|
+
return proxy;
|
|
95
|
+
}
|
|
96
|
+
/** Claude Code's own bounds where it has them (120 s clone; 5 MiB / 10 s JSON; 256 MiB archives), a little more time for slow links. */
|
|
97
|
+
export const DEFAULT_LIMITS = {
|
|
98
|
+
fetchMs: 180_000,
|
|
99
|
+
lookupMs: 30_000,
|
|
100
|
+
operationMs: 600_000,
|
|
101
|
+
jsonBytes: 5 * 1024 * 1024,
|
|
102
|
+
jsonMs: 30_000,
|
|
103
|
+
archiveBytes: 256 * 1024 * 1024,
|
|
104
|
+
tree: REPOSITORY_LIMITS,
|
|
105
|
+
pollMs: 250,
|
|
106
|
+
};
|
|
107
|
+
function processRunner(resolveCommand) {
|
|
108
|
+
return (_command, args, options) => new Promise((resolvePromise, reject) => {
|
|
109
|
+
const launch = resolveCommand(args);
|
|
110
|
+
execFile(launch.command, [...launch.args], {
|
|
111
|
+
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
|
|
112
|
+
...(options.signal !== undefined ? { signal: options.signal } : {}),
|
|
113
|
+
timeout: options.timeoutMs,
|
|
114
|
+
windowsHide: true,
|
|
115
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
116
|
+
env: options.env ?? process.env,
|
|
117
|
+
}, (error, stdout, stderr) => {
|
|
118
|
+
if (error === null) {
|
|
119
|
+
resolvePromise(stdout);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const failure = error;
|
|
123
|
+
if (failure.code === 'ENOENT') {
|
|
124
|
+
reject(Object.assign(new Error(`${launch.command} is not installed`), { code: 'ENOENT' }));
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const detail = scrub(String(stderr)).trim().split(/\r?\n/u).filter(line => line.length > 0 && !/^warning: filtering not recognized/u.test(line)).slice(-3).join(' | ');
|
|
128
|
+
reject(new Error(failure.killed === true && failure.name !== 'AbortError' ? `${launch.command} ${args.find(arg => !arg.startsWith('-') && !arg.includes('=')) ?? ''} timed out after ${String(Math.round(options.timeoutMs / 1000))} s` : detail.length > 0 ? detail : scrub(messageOf(error))));
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Where the URL scheme ending at `colon` (the `:` of a `://`) starts, as
|
|
134
|
+
* `\b[a-z][a-z0-9+.-]*` finds it, any length. Scans, here and below, rather than
|
|
135
|
+
* patterns: a pattern tried from every letter of a long run is quadratic.
|
|
136
|
+
*/
|
|
137
|
+
function schemeStart(text, colon) {
|
|
138
|
+
let start = colon;
|
|
139
|
+
while (start > 0 && /[a-z0-9+.-]/iu.test(text[start - 1] ?? ''))
|
|
140
|
+
start--;
|
|
141
|
+
for (let at = start; at < colon; at++) {
|
|
142
|
+
if (/[a-z]/iu.test(text[at] ?? '') && (at === 0 || !/\w/u.test(text[at - 1] ?? '')))
|
|
143
|
+
return at;
|
|
144
|
+
}
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
/** Where the run from `from` of characters not in `stop` ends. */
|
|
148
|
+
function runEnd(text, from, stop) {
|
|
149
|
+
let end = from;
|
|
150
|
+
while (end < text.length && !stop.test(text[end] ?? ''))
|
|
151
|
+
end++;
|
|
152
|
+
return end;
|
|
153
|
+
}
|
|
154
|
+
/** A text with the credentials of any URL in it replaced (proxy passwords never reach a message). */
|
|
155
|
+
export function redact(text) {
|
|
156
|
+
let out = '';
|
|
157
|
+
let cursor = 0;
|
|
158
|
+
for (let colon = text.indexOf('://'); colon !== -1; colon = text.indexOf('://', colon + 3)) {
|
|
159
|
+
if (schemeStart(text, colon) === undefined)
|
|
160
|
+
continue;
|
|
161
|
+
const end = runEnd(text, colon + 3, /[/@\s]/u);
|
|
162
|
+
if (text[end] !== '@')
|
|
163
|
+
continue;
|
|
164
|
+
out += `${text.slice(cursor, colon + 3)}***@`;
|
|
165
|
+
cursor = end + 1;
|
|
166
|
+
}
|
|
167
|
+
return out + text.slice(cursor);
|
|
168
|
+
}
|
|
169
|
+
/** A text with every URL in it shown as {@link shown} shows one (for what git and npm write to stderr). */
|
|
170
|
+
export function scrub(text) {
|
|
171
|
+
const redacted = redact(text);
|
|
172
|
+
let out = '';
|
|
173
|
+
let cursor = 0;
|
|
174
|
+
for (let colon = redacted.indexOf('://'); colon !== -1; colon = redacted.indexOf('://', Math.max(colon + 3, cursor))) {
|
|
175
|
+
const start = schemeStart(redacted, colon);
|
|
176
|
+
if (start === undefined || start < cursor)
|
|
177
|
+
continue;
|
|
178
|
+
const end = runEnd(redacted, colon + 3, /[\s'"<>]/u);
|
|
179
|
+
if (end === colon + 3)
|
|
180
|
+
continue;
|
|
181
|
+
out += redacted.slice(cursor, start) + shown(redacted.slice(start, end));
|
|
182
|
+
cursor = end;
|
|
183
|
+
}
|
|
184
|
+
return out + redacted.slice(cursor);
|
|
185
|
+
}
|
|
186
|
+
/** A URL as messages show it: no credentials, no query string (signed URLs), no fragment. */
|
|
187
|
+
export function shown(url) {
|
|
188
|
+
try {
|
|
189
|
+
const parsed = new URL(String(url));
|
|
190
|
+
return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return redact(String(url)).replace(/[?#].*$/su, '');
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/** Statuses whose answer has no body. */
|
|
197
|
+
const NO_BODY = new Set([204, 205, 304]);
|
|
198
|
+
/** A web Response over a Node response. */
|
|
199
|
+
function webResponse(response) {
|
|
200
|
+
const status = response.statusCode ?? 0;
|
|
201
|
+
if (!Number.isInteger(status) || status < 200 || status > 599)
|
|
202
|
+
throw new HarnessError('fetch-failed', `the server answered with status ${String(status)}, which is not an HTTP answer`);
|
|
203
|
+
const headers = new Headers();
|
|
204
|
+
for (const [key, value] of Object.entries(response.headers))
|
|
205
|
+
for (const item of [value ?? []].flat())
|
|
206
|
+
headers.append(key, item);
|
|
207
|
+
if (NO_BODY.has(status))
|
|
208
|
+
response.resume();
|
|
209
|
+
return new Response(NO_BODY.has(status) ? null : Readable.toWeb(response), { status, statusText: response.statusMessage ?? '', headers });
|
|
210
|
+
}
|
|
211
|
+
function proxyAuthorization(proxy) {
|
|
212
|
+
if (proxy.username.length === 0)
|
|
213
|
+
return {};
|
|
214
|
+
return { 'proxy-authorization': `Basic ${Buffer.from(`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`).toString('base64')}` };
|
|
215
|
+
}
|
|
216
|
+
/** Settle a request with its response; a response that cannot be read is destroyed and the request rejected, never thrown from the callback. */
|
|
217
|
+
function settle(response, resolvePromise, reject) {
|
|
218
|
+
try {
|
|
219
|
+
resolvePromise(webResponse(response));
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
response.destroy();
|
|
223
|
+
response.socket?.destroy();
|
|
224
|
+
reject(error);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** A connection to the proxy itself (TLS for an https:// proxy). */
|
|
228
|
+
function proxyRequest(proxy, options) {
|
|
229
|
+
const base = { host: proxy.hostname.replace(/^\[|\]$/gu, ''), port: Number(proxy.port || (proxy.protocol === 'https:' ? 443 : 80)), agent: false };
|
|
230
|
+
return proxy.protocol === 'https:' ? httpsRequest({ ...base, ...options, servername: base.host }) : httpRequest({ ...base, ...options });
|
|
231
|
+
}
|
|
232
|
+
/** A tunnel through the proxy to `host:port` (HTTP CONNECT). */
|
|
233
|
+
function tunnel(proxy, host, port, signal) {
|
|
234
|
+
return new Promise((resolvePromise, reject) => {
|
|
235
|
+
const authority = `${isIP(host) === 6 ? `[${host}]` : host}:${String(port)}`;
|
|
236
|
+
const request = proxyRequest(proxy, { method: 'CONNECT', path: authority, headers: { host: authority, ...proxyAuthorization(proxy) }, signal });
|
|
237
|
+
request.on('connect', (response, socket) => {
|
|
238
|
+
if (response.statusCode === 200 && !signal.aborted)
|
|
239
|
+
resolvePromise(socket);
|
|
240
|
+
else if (response.statusCode === 200) {
|
|
241
|
+
socket.destroy();
|
|
242
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
socket.destroy();
|
|
246
|
+
reject(new HarnessError('fetch-failed', `the proxy refused to connect to ${host} (${String(response.statusCode)})`));
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
request.on('error', reject);
|
|
250
|
+
request.end();
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* TLS over a proxy tunnel, verified against the target's name (or IP address,
|
|
255
|
+
* which gets no SNI). The handshake is bound by `signal` (the operation's
|
|
256
|
+
* deadline and cancellation); when it fails, closes or is stopped, both the
|
|
257
|
+
* TLS socket and the tunnel are destroyed.
|
|
258
|
+
*/
|
|
259
|
+
function secureTunnel(socket, host, ca, signal) {
|
|
260
|
+
return new Promise((resolvePromise, reject) => {
|
|
261
|
+
const secure = tlsConnect({ socket, host, ...(isIP(host) === 0 ? { servername: host } : {}), ...(ca !== undefined ? { ca } : {}), ALPNProtocols: ['http/1.1'] });
|
|
262
|
+
let settled = false;
|
|
263
|
+
const closed = () => { fail(new HarnessError('fetch-failed', `the connection to ${host} closed during the TLS handshake`)); };
|
|
264
|
+
const aborted = () => { fail(signal.reason instanceof Error ? signal.reason : Object.assign(new Error('timed out'), { name: 'TimeoutError' })); };
|
|
265
|
+
const done = () => {
|
|
266
|
+
settled = true;
|
|
267
|
+
signal.removeEventListener('abort', aborted);
|
|
268
|
+
secure.off('error', fail).off('close', closed);
|
|
269
|
+
socket.off('close', closed).off('end', closed);
|
|
270
|
+
};
|
|
271
|
+
function fail(error) {
|
|
272
|
+
if (settled)
|
|
273
|
+
return;
|
|
274
|
+
done();
|
|
275
|
+
secure.destroy();
|
|
276
|
+
socket.destroy();
|
|
277
|
+
reject(error);
|
|
278
|
+
}
|
|
279
|
+
secure.once('secureConnect', () => {
|
|
280
|
+
if (settled)
|
|
281
|
+
return;
|
|
282
|
+
done();
|
|
283
|
+
resolvePromise(secure);
|
|
284
|
+
});
|
|
285
|
+
secure.on('error', fail).on('close', closed);
|
|
286
|
+
socket.on('close', closed).on('end', closed);
|
|
287
|
+
if (signal.aborted)
|
|
288
|
+
aborted();
|
|
289
|
+
else
|
|
290
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* {@link PinnedFetch} over `http(s).request`: directly, its `lookup` answering
|
|
295
|
+
* with the address checked; or through a proxy, a CONNECT tunnel carrying TLS
|
|
296
|
+
* for https (the request is written on that socket alone, with no agent of its
|
|
297
|
+
* own), an absolute URL for http. No connection reuse. `ca` replaces the
|
|
298
|
+
* trusted certificates (tests).
|
|
299
|
+
*/
|
|
300
|
+
export function httpClient(options = {}) {
|
|
301
|
+
const ca = options.ca;
|
|
302
|
+
return async (url, init) => {
|
|
303
|
+
const target = new URL(url);
|
|
304
|
+
const host = target.hostname.replace(/^\[|\]$/gu, '');
|
|
305
|
+
if (init.proxy !== undefined) {
|
|
306
|
+
const proxy = new URL(init.proxy);
|
|
307
|
+
if (target.protocol === 'http:') {
|
|
308
|
+
return new Promise((resolvePromise, reject) => {
|
|
309
|
+
const request = proxyRequest(proxy, { method: 'GET', path: target.href, headers: { ...init.headers, host: target.host, ...proxyAuthorization(proxy) }, signal: init.signal });
|
|
310
|
+
request.on('response', (response) => { settle(response, resolvePromise, reject); });
|
|
311
|
+
request.on('error', reject);
|
|
312
|
+
request.end();
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
const socket = await tunnel(proxy, host, Number(target.port || 443), init.signal);
|
|
316
|
+
const secure = await secureTunnel(socket, host, ca, init.signal);
|
|
317
|
+
return new Promise((resolvePromise, reject) => {
|
|
318
|
+
// No `agent`: Node then writes the request on the socket createConnection returns (an agent would open its own, directly).
|
|
319
|
+
const request = httpRequest({
|
|
320
|
+
method: 'GET',
|
|
321
|
+
path: `${target.pathname}${target.search}`,
|
|
322
|
+
headers: { ...init.headers, host: target.host },
|
|
323
|
+
signal: init.signal,
|
|
324
|
+
createConnection: () => secure,
|
|
325
|
+
}, (response) => { settle(response, resolvePromise, reject); });
|
|
326
|
+
request.on('error', (error) => { secure.destroy(); reject(error); });
|
|
327
|
+
request.end();
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
return new Promise((resolvePromise, reject) => {
|
|
331
|
+
const request = (target.protocol === 'https:' ? httpsRequest : httpRequest)(target, {
|
|
332
|
+
method: 'GET',
|
|
333
|
+
headers: init.headers,
|
|
334
|
+
signal: init.signal,
|
|
335
|
+
agent: false,
|
|
336
|
+
...(ca !== undefined ? { ca } : {}),
|
|
337
|
+
lookup: (_host, lookupOptions, callback) => {
|
|
338
|
+
if (lookupOptions.all === true)
|
|
339
|
+
callback(null, [{ address: init.address, family: init.family ?? 4 }]);
|
|
340
|
+
else
|
|
341
|
+
callback(null, init.address, init.family ?? 4);
|
|
342
|
+
},
|
|
343
|
+
}, (response) => { settle(response, resolvePromise, reject); });
|
|
344
|
+
request.on('error', reject);
|
|
345
|
+
request.end();
|
|
346
|
+
});
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
/** The machine's git, npm, HTTP and resolver. */
|
|
350
|
+
export const SYSTEM_DEPS = {
|
|
351
|
+
fetch: httpClient(),
|
|
352
|
+
git: processRunner(args => ({ command: 'git', args })),
|
|
353
|
+
npm: processRunner(args => npmLaunch(args)),
|
|
354
|
+
lookup: async (host) => (await dnsLookup(host, { all: true, verbatim: true })).map(entry => entry.address),
|
|
355
|
+
};
|
|
356
|
+
/** Addresses a marketplace may not lead to: this computer, private and shared networks, link-local, multicast, reserved and documentation ranges. */
|
|
357
|
+
const NOT_PUBLIC_V4 = new BlockList();
|
|
358
|
+
/** Kept apart: a BlockList also matches IPv4 addresses against IPv4-mapped IPv6 ranges. */
|
|
359
|
+
const NOT_PUBLIC_V6 = new BlockList();
|
|
360
|
+
for (const [network, bits] of [
|
|
361
|
+
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12],
|
|
362
|
+
['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['198.51.100.0', 24],
|
|
363
|
+
['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4],
|
|
364
|
+
])
|
|
365
|
+
NOT_PUBLIC_V4.addSubnet(network, bits, 'ipv4');
|
|
366
|
+
for (const [network, bits] of [
|
|
367
|
+
['::', 127], ['::ffff:0:0', 96], ['64:ff9b::', 96], ['64:ff9b:1::', 48], ['100::', 64], ['2001::', 23], ['2001:db8::', 32],
|
|
368
|
+
['2002::', 16], ['fc00::', 7], ['fe80::', 10], ['fec0::', 10], ['ff00::', 8],
|
|
369
|
+
])
|
|
370
|
+
NOT_PUBLIC_V6.addSubnet(network, bits, 'ipv6');
|
|
371
|
+
/** Whether an IP address is on the public internet. */
|
|
372
|
+
export function isPublicAddress(address) {
|
|
373
|
+
const family = isIP(address);
|
|
374
|
+
if (family === 0)
|
|
375
|
+
return false;
|
|
376
|
+
return family === 4 ? !NOT_PUBLIC_V4.check(address, 'ipv4') : !NOT_PUBLIC_V6.check(address, 'ipv6');
|
|
377
|
+
}
|
|
378
|
+
function cacheKey(...parts) {
|
|
379
|
+
return createHash('sha256').update(parts.join('\0')).digest('hex').slice(0, 24);
|
|
380
|
+
}
|
|
381
|
+
function temporary(parent) {
|
|
382
|
+
mkdirSync(parent, { recursive: true });
|
|
383
|
+
return join(parent, `.tmp-${randomBytes(6).toString('hex')}`);
|
|
384
|
+
}
|
|
385
|
+
function writeJson(path, value) {
|
|
386
|
+
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
387
|
+
}
|
|
388
|
+
function hostOf(url) {
|
|
389
|
+
try {
|
|
390
|
+
return new URL(url).host;
|
|
391
|
+
}
|
|
392
|
+
catch {
|
|
393
|
+
return url;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
/** Why a download failed, in words a person can act on. */
|
|
397
|
+
function networkError(url, error) {
|
|
398
|
+
if (error instanceof HarnessError)
|
|
399
|
+
return error;
|
|
400
|
+
const cause = error?.cause;
|
|
401
|
+
const name = error?.name;
|
|
402
|
+
const own = error?.code;
|
|
403
|
+
const code = typeof own === 'string' ? own : typeof cause?.code === 'string' ? cause.code : name === 'TimeoutError' || name === 'AbortError' ? 'timed out' : redact(messageOf(error));
|
|
404
|
+
return new HarnessError('fetch-failed', `cannot reach ${hostOf(url)} (${code})`, {
|
|
405
|
+
cause: error,
|
|
406
|
+
suggestion: 'Check the network connection. Harness Forge\'s own downloads do not go through a proxy; behind one, install git (it reads HTTPS_PROXY).',
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/** An HTTP error answer, with GitHub's rate limit told apart from a missing repository. */
|
|
410
|
+
function httpError(url, response) {
|
|
411
|
+
const status = response.status;
|
|
412
|
+
const github = /(?:^|\.)github(?:usercontent)?\.com$/iu.test(url.hostname);
|
|
413
|
+
const remaining = response.headers.get('x-ratelimit-remaining');
|
|
414
|
+
if (github && (status === 429 || (status === 403 && remaining === '0'))) {
|
|
415
|
+
const reset = Number(response.headers.get('x-ratelimit-reset') ?? '');
|
|
416
|
+
const when = Number.isFinite(reset) && reset > 0 ? ` until ${new Date(reset * 1000).toISOString().slice(11, 16)} UTC` : '';
|
|
417
|
+
return new HarnessError('fetch-failed', `GitHub refuses more requests from this network for now (rate limit, HTTP ${String(status)})${when}`, {
|
|
418
|
+
suggestion: 'Install git: cloning does not count against GitHub\'s API limit. Or try again later.',
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
return new HarnessError('fetch-failed', `${shown(url)} answered ${String(status)}`, status === 404 ? { suggestion: 'Check the name and that the repository is public.' } : status === 401 || status === 403 ? { suggestion: 'The source is private or refuses this network; Harness Forge fetches public sources without signing in.' } : undefined);
|
|
422
|
+
}
|
|
423
|
+
function tooLargeError(what, limits) {
|
|
424
|
+
return new HarnessError('fetch-failed', `${what} is larger than Harness Forge accepts (${String(Math.round(limits.maxBytes / 1024 / 1024))} MiB or ${String(limits.maxEntries)} files)`);
|
|
425
|
+
}
|
|
426
|
+
function timedOut(what, ms) {
|
|
427
|
+
return new HarnessError('fetch-failed', `${what} timed out after ${String(Math.round(ms / 1000))} s`, { suggestion: 'Check the network connection and try again.' });
|
|
428
|
+
}
|
|
429
|
+
/** A version npm would install as it is: `1.2.3`, `1.2.3-beta.1`, no range. */
|
|
430
|
+
const EXACT_VERSION = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
|
|
431
|
+
/** A dist-tag (`latest`, `next`). */
|
|
432
|
+
const DIST_TAG = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/u;
|
|
433
|
+
const SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/u;
|
|
434
|
+
/** A registry document (npm's abbreviated form): large packages have many versions. */
|
|
435
|
+
const PACKUMENT_BYTES = 64 * 1024 * 1024;
|
|
436
|
+
/** Fetches into `<root>/cache` (checkouts to browse and copy from) and the directories its callers name. */
|
|
437
|
+
export class RemoteFetcher {
|
|
438
|
+
root;
|
|
439
|
+
deps;
|
|
440
|
+
limits;
|
|
441
|
+
gitVersion;
|
|
442
|
+
constructor(root, deps = SYSTEM_DEPS, limits = DEFAULT_LIMITS) {
|
|
443
|
+
this.root = root;
|
|
444
|
+
this.deps = deps;
|
|
445
|
+
this.limits = limits;
|
|
446
|
+
}
|
|
447
|
+
/** A new operation: every step taken with it shares its wall-clock bound. */
|
|
448
|
+
context(trust, userHosts = []) {
|
|
449
|
+
return { trust, signal: AbortSignal.timeout(this.limits.operationMs), deadline: Date.now() + this.limits.operationMs, userHosts: userHosts.map(host => host.toLowerCase()) };
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Refuse a host Harness Forge may not reach through a proxy: GitHub and npm
|
|
453
|
+
* ({@link PROXY_HOSTS}), the configured npm registry, and (for what the
|
|
454
|
+
* person pasted, not what a marketplace names) the hosts they pasted.
|
|
455
|
+
*/
|
|
456
|
+
allowProxied(url, context) {
|
|
457
|
+
const bare = url.hostname.toLowerCase().replace(/^\[|\]$/gu, '');
|
|
458
|
+
// GitHub and npm only as themselves: https on port 443.
|
|
459
|
+
if (PROXY_HOSTS.has(bare) && url.protocol === 'https:' && (url.port === '' || url.port === '443'))
|
|
460
|
+
return;
|
|
461
|
+
if (url.origin === new URL(this.configuredRegistry()).origin)
|
|
462
|
+
return;
|
|
463
|
+
if (context.trust === 'user' && context.userHosts.includes(bare))
|
|
464
|
+
return;
|
|
465
|
+
throw new HarnessError('fetch-failed', `behind a proxy, Harness Forge reaches only GitHub, npm's registry, your npm registry and the sources you paste, not ${bare}`, {
|
|
466
|
+
suggestion: `If you trust ${bare}, paste that source yourself, or add it to NO_PROXY if it can be reached directly.`,
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
/** The same operation on another's say-so (an entry of a marketplace being read). */
|
|
470
|
+
static as(context, trust) {
|
|
471
|
+
return { ...context, trust };
|
|
472
|
+
}
|
|
473
|
+
remaining(context, stepMs, what) {
|
|
474
|
+
const left = context.deadline - Date.now();
|
|
475
|
+
if (left <= 0 || context.signal.aborted)
|
|
476
|
+
throw timedOut(what, this.limits.operationMs);
|
|
477
|
+
return Math.min(stepMs, left);
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Run a subprocess within the operation's bound; with `watch`, the
|
|
481
|
+
* directory it writes is measured while it runs and the process killed
|
|
482
|
+
* once it is past the size bound.
|
|
483
|
+
*/
|
|
484
|
+
async run(runner, command, args, context, options) {
|
|
485
|
+
const timeoutMs = this.remaining(context, options.stepMs, options.what);
|
|
486
|
+
const controller = new AbortController();
|
|
487
|
+
const stop = (reason) => {
|
|
488
|
+
if (!controller.signal.aborted)
|
|
489
|
+
controller.abort(reason);
|
|
490
|
+
};
|
|
491
|
+
const outer = () => { stop(timedOut(options.what, this.limits.operationMs)); };
|
|
492
|
+
context.signal.addEventListener('abort', outer, { once: true });
|
|
493
|
+
const watch = options.watch;
|
|
494
|
+
const timer = watch === undefined ? undefined : setInterval(() => {
|
|
495
|
+
if (treeSize(watch, this.limits.tree).over)
|
|
496
|
+
stop(tooLargeError(options.what, this.limits.tree));
|
|
497
|
+
}, this.limits.pollMs);
|
|
498
|
+
try {
|
|
499
|
+
const out = await runner(command, args, { ...(options.cwd !== undefined ? { cwd: options.cwd } : {}), ...(options.env !== undefined ? { env: options.env } : {}), timeoutMs, signal: controller.signal });
|
|
500
|
+
if (watch !== undefined && treeSize(watch, this.limits.tree).over)
|
|
501
|
+
throw tooLargeError(options.what, this.limits.tree);
|
|
502
|
+
return out;
|
|
503
|
+
}
|
|
504
|
+
catch (error) {
|
|
505
|
+
if (controller.signal.aborted && controller.signal.reason instanceof HarnessError)
|
|
506
|
+
throw controller.signal.reason;
|
|
507
|
+
throw error;
|
|
508
|
+
}
|
|
509
|
+
finally {
|
|
510
|
+
if (timer !== undefined)
|
|
511
|
+
clearInterval(timer);
|
|
512
|
+
context.signal.removeEventListener('abort', outer);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
// --- the network policy -------------------------------------------------------
|
|
516
|
+
/** A host's addresses, within the operation's bound (and the lookup bound). */
|
|
517
|
+
async resolveHost(host, context) {
|
|
518
|
+
const ms = this.remaining(context, this.limits.lookupMs, `resolving ${host}`);
|
|
519
|
+
let timer;
|
|
520
|
+
try {
|
|
521
|
+
return await Promise.race([
|
|
522
|
+
this.deps.lookup(host),
|
|
523
|
+
new Promise((_resolve, reject) => { timer = setTimeout(() => { reject(new HarnessError('fetch-failed', `resolving ${host} timed out`)); }, ms); }),
|
|
524
|
+
]);
|
|
525
|
+
}
|
|
526
|
+
catch (error) {
|
|
527
|
+
throw networkError(`https://${host}/`, error);
|
|
528
|
+
}
|
|
529
|
+
finally {
|
|
530
|
+
clearTimeout(timer);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* The addresses of a host, refused (with `checked`) when any of them is not
|
|
535
|
+
* on the public internet or the name does not resolve.
|
|
536
|
+
*/
|
|
537
|
+
async addresses(host, context, checked) {
|
|
538
|
+
const bare = host.replace(/^\[|\]$/gu, '');
|
|
539
|
+
const addresses = isIP(bare) !== 0 ? [bare] : await this.resolveHost(bare, context);
|
|
540
|
+
if (addresses.length === 0)
|
|
541
|
+
throw new HarnessError('fetch-failed', `${bare} does not resolve`);
|
|
542
|
+
const local = checked ? addresses.find(address => !isPublicAddress(address)) : undefined;
|
|
543
|
+
if (local !== undefined) {
|
|
544
|
+
throw new HarnessError('fetch-failed', `a marketplace or a redirect may not send Harness Forge to ${bare} (${local}): that address is on this computer or a local network`, {
|
|
545
|
+
suggestion: 'To install from your own network, paste the final address of that source yourself.',
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
return addresses;
|
|
549
|
+
}
|
|
550
|
+
/** Refuse a URL the operation may not request: only https for a marketplace, http(s) for the person. */
|
|
551
|
+
allowHttp(url, context) {
|
|
552
|
+
const allowed = context.trust === 'marketplace' ? ['https:'] : ['https:', 'http:'];
|
|
553
|
+
if (!allowed.includes(url.protocol))
|
|
554
|
+
throw new HarnessError('fetch-failed', `${context.trust === 'marketplace' ? 'only https downloads are fetched for a marketplace' : 'only http(s) downloads are supported'}: ${shown(url)}`);
|
|
555
|
+
if (url.username.length > 0 || url.password.length > 0)
|
|
556
|
+
throw new HarnessError('fetch-failed', `a download URL may not carry credentials: ${url.host}`);
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Bytes of a URL, refused past `maxBytes` (declared or received) or
|
|
560
|
+
* `timeoutMs`. Each hop connects to the address checked for it; redirects
|
|
561
|
+
* are followed by hand and, wherever the first hop pointed, every later one
|
|
562
|
+
* must be a public address.
|
|
563
|
+
*/
|
|
564
|
+
async download(url, maxBytes, timeoutMs, context, headers = {}) {
|
|
565
|
+
let current;
|
|
566
|
+
try {
|
|
567
|
+
current = new URL(url);
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
throw new HarnessError('fetch-failed', `not a URL: ${shown(url)}`);
|
|
571
|
+
}
|
|
572
|
+
const signal = AbortSignal.any([context.signal, AbortSignal.timeout(this.remaining(context, timeoutMs, `downloading ${hostOf(url)}`))]);
|
|
573
|
+
for (let hop = 0;; hop += 1) {
|
|
574
|
+
this.allowHttp(current, context);
|
|
575
|
+
const proxy = proxyFor(current);
|
|
576
|
+
let target;
|
|
577
|
+
if (proxy !== undefined) {
|
|
578
|
+
// The proxy resolves the name: only hosts on the allowlist are asked for.
|
|
579
|
+
this.allowProxied(current, context);
|
|
580
|
+
target = { proxy: proxy.href };
|
|
581
|
+
}
|
|
582
|
+
else {
|
|
583
|
+
const [address] = await this.addresses(current.hostname, context, context.trust === 'marketplace' || hop > 0);
|
|
584
|
+
target = { address: address, family: isIP(address) === 6 ? 6 : 4 };
|
|
585
|
+
}
|
|
586
|
+
let response;
|
|
587
|
+
try {
|
|
588
|
+
response = await this.deps.fetch(current.href, { headers: { 'user-agent': 'harness-forge', ...headers }, signal, ...target });
|
|
589
|
+
}
|
|
590
|
+
catch (error) {
|
|
591
|
+
throw networkError(shown(current), error);
|
|
592
|
+
}
|
|
593
|
+
if (response.status >= 300 && response.status < 400 && response.status !== 304) {
|
|
594
|
+
const location = response.headers.get('location');
|
|
595
|
+
await response.body?.cancel().catch(() => undefined);
|
|
596
|
+
if (location === null)
|
|
597
|
+
throw new HarnessError('fetch-failed', `${shown(current)} redirected without saying where`);
|
|
598
|
+
if (hop >= 5)
|
|
599
|
+
throw new HarnessError('fetch-failed', `${shown(url)} redirected too many times`);
|
|
600
|
+
const next = new URL(location, current);
|
|
601
|
+
// A redirect may not downgrade an https download.
|
|
602
|
+
if (current.protocol === 'https:' && next.protocol !== 'https:')
|
|
603
|
+
throw new HarnessError('fetch-failed', `${shown(current)} redirected to a non-https address`);
|
|
604
|
+
current = next;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
if (!response.ok) {
|
|
608
|
+
const error = httpError(current, response);
|
|
609
|
+
await response.body?.cancel().catch(() => undefined);
|
|
610
|
+
throw error;
|
|
611
|
+
}
|
|
612
|
+
const declared = Number(response.headers.get('content-length') ?? '0');
|
|
613
|
+
const tooLarge = () => new HarnessError('fetch-failed', `${shown(url)} is larger than ${String(Math.round(maxBytes / 1024 / 1024))} MiB`);
|
|
614
|
+
if (declared > maxBytes) {
|
|
615
|
+
await response.body?.cancel().catch(() => undefined);
|
|
616
|
+
throw tooLarge();
|
|
617
|
+
}
|
|
618
|
+
const chunks = [];
|
|
619
|
+
let received = 0;
|
|
620
|
+
try {
|
|
621
|
+
const reader = response.body?.getReader();
|
|
622
|
+
if (reader === undefined)
|
|
623
|
+
return Buffer.alloc(0);
|
|
624
|
+
for (;;) {
|
|
625
|
+
const { done, value } = await reader.read();
|
|
626
|
+
if (done)
|
|
627
|
+
break;
|
|
628
|
+
received += value.byteLength;
|
|
629
|
+
if (received > maxBytes) {
|
|
630
|
+
await reader.cancel().catch(() => undefined);
|
|
631
|
+
throw tooLarge();
|
|
632
|
+
}
|
|
633
|
+
chunks.push(Buffer.from(value));
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
catch (error) {
|
|
637
|
+
throw networkError(shown(current), error);
|
|
638
|
+
}
|
|
639
|
+
return Buffer.concat(chunks);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
/** A hosted JSON document (a `marketplace.json`, a registry document). */
|
|
643
|
+
async json(url, context = this.context('user'), maxBytes = this.limits.jsonBytes, accept = 'application/json') {
|
|
644
|
+
const bytes = await this.download(url, maxBytes, this.limits.jsonMs, context, { accept });
|
|
645
|
+
try {
|
|
646
|
+
const value = JSON.parse(bytes.toString('utf8'));
|
|
647
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value))
|
|
648
|
+
return value;
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
651
|
+
// Reported below.
|
|
652
|
+
}
|
|
653
|
+
throw new HarnessError('manifest-invalid', `${shown(url)} is not a JSON object`);
|
|
654
|
+
}
|
|
655
|
+
// --- git ------------------------------------------------------------------
|
|
656
|
+
/** Empty hooks, template and working directories and an empty global configuration: what git reads instead of this computer's. */
|
|
657
|
+
isolation() {
|
|
658
|
+
const base = join(this.root, 'git-isolation');
|
|
659
|
+
const paths = { hooks: join(base, 'hooks'), template: join(base, 'template'), config: join(base, 'gitconfig'), empty: join(base, 'cwd') };
|
|
660
|
+
for (const dir of [paths.hooks, paths.template, paths.empty])
|
|
661
|
+
mkdirSync(dir, { recursive: true });
|
|
662
|
+
if (!existsSync(paths.config))
|
|
663
|
+
writeFileSync(paths.config, '');
|
|
664
|
+
return paths;
|
|
665
|
+
}
|
|
666
|
+
/** The environment git runs in: no `GIT_*` variable of this process, no system or global configuration, no prompts, no LFS downloads. */
|
|
667
|
+
gitEnv() {
|
|
668
|
+
const env = {};
|
|
669
|
+
// No proxy variable either: git is told the route Harness Forge chose (gitOptions), not left to read curl's.
|
|
670
|
+
for (const [key, value] of Object.entries(process.env))
|
|
671
|
+
if (value !== undefined && !/^GIT_/iu.test(key) && !/^(?:https?|all|no)_proxy$/iu.test(key) && key !== 'SSH_ASKPASS')
|
|
672
|
+
env[key] = value;
|
|
673
|
+
return {
|
|
674
|
+
...env,
|
|
675
|
+
// The empty working directory and the checkouts are inside the data directory: no repository around it is found.
|
|
676
|
+
GIT_CEILING_DIRECTORIES: resolve(this.root),
|
|
677
|
+
GIT_CONFIG_NOSYSTEM: '1',
|
|
678
|
+
GIT_CONFIG_GLOBAL: this.isolation().config,
|
|
679
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
680
|
+
GIT_LFS_SKIP_SMUDGE: '1',
|
|
681
|
+
GCM_INTERACTIVE: 'never',
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
/** git's version, asked once; undefined when git is not installed. */
|
|
685
|
+
version() {
|
|
686
|
+
this.gitVersion ??= this.deps.git('git', ['--version'], { cwd: this.isolation().empty, timeoutMs: this.limits.lookupMs, env: this.gitEnv() }).then((out) => {
|
|
687
|
+
const match = /(\d+)\.(\d+)/u.exec(out);
|
|
688
|
+
return match === null ? [2, 0] : [Number(match[1]), Number(match[2])];
|
|
689
|
+
}, () => undefined);
|
|
690
|
+
return this.gitVersion;
|
|
691
|
+
}
|
|
692
|
+
/** Whether git is installed. */
|
|
693
|
+
async hasGit() {
|
|
694
|
+
return await this.version() !== undefined;
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* Whether git may fetch `url` in this operation. For a marketplace's URL,
|
|
698
|
+
* git must connect to the addresses Harness Forge checked: that needs
|
|
699
|
+
* `http.curloptResolve` (git 2.37+) and no proxy resolving hosts instead;
|
|
700
|
+
* behind a proxy only github.com is fetched with git.
|
|
701
|
+
*/
|
|
702
|
+
async gitFor(url, context) {
|
|
703
|
+
const version = await this.version();
|
|
704
|
+
if (version === undefined)
|
|
705
|
+
return { use: false, why: 'git is not installed' };
|
|
706
|
+
if (context.trust === 'user')
|
|
707
|
+
return { use: true };
|
|
708
|
+
if (version[0] < 2 || (version[0] === 2 && version[1] < 37))
|
|
709
|
+
return { use: false, why: 'git older than 2.37 cannot be held to the addresses Harness Forge checked' };
|
|
710
|
+
let parsed;
|
|
711
|
+
try {
|
|
712
|
+
parsed = new URL(url);
|
|
713
|
+
}
|
|
714
|
+
catch {
|
|
715
|
+
// Not an https URL: gitOptions refuses it.
|
|
716
|
+
return { use: true };
|
|
717
|
+
}
|
|
718
|
+
if (proxyFor(parsed) !== undefined) {
|
|
719
|
+
// The proxy resolves hosts for git: only the hosts Harness Forge may reach through it.
|
|
720
|
+
try {
|
|
721
|
+
this.allowProxied(parsed, context);
|
|
722
|
+
}
|
|
723
|
+
catch (error) {
|
|
724
|
+
return { use: false, why: messageOf(error) };
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return { use: true };
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* The `-c` options every git command for a URL runs with, and the URL as
|
|
731
|
+
* Harness Forge read it (what git is given): nothing of this computer's that
|
|
732
|
+
* runs code, only the URL's transport, no redirects, the proxy Harness Forge
|
|
733
|
+
* chose (or none), and for a marketplace HTTPS pinned to the public
|
|
734
|
+
* addresses checked.
|
|
735
|
+
*/
|
|
736
|
+
async gitOptions(raw, context) {
|
|
737
|
+
if (raw.startsWith('-') || /\s/u.test(raw))
|
|
738
|
+
throw new HarnessError('unsupported-source', `not a git URL: ${shown(raw)}`);
|
|
739
|
+
const transport = gitTransport(raw);
|
|
740
|
+
if (context.trust === 'marketplace' && transport !== 'https')
|
|
741
|
+
throw new HarnessError('unsupported-source', `only https git URLs are fetched for a marketplace entry: ${shown(raw)}`);
|
|
742
|
+
if (transport === undefined)
|
|
743
|
+
throw new HarnessError('unsupported-source', `git URLs must use https, http, ssh, git or file: ${shown(raw)}`);
|
|
744
|
+
// `user@host:path` is not a URL; every other form is given to git as it was parsed here.
|
|
745
|
+
const parsed = /^[a-z][a-z0-9+.-]*:\/\//iu.test(raw) ? new URL(raw) : undefined;
|
|
746
|
+
const url = parsed?.href ?? raw;
|
|
747
|
+
const { hooks } = this.isolation();
|
|
748
|
+
const options = [
|
|
749
|
+
`core.hooksPath=${hooks}`,
|
|
750
|
+
'core.fsmonitor=false',
|
|
751
|
+
'protocol.allow=never',
|
|
752
|
+
`protocol.${transport}.allow=always`,
|
|
753
|
+
...(transport !== 'file' ? ['protocol.file.allow=never'] : []),
|
|
754
|
+
'submodule.recurse=false',
|
|
755
|
+
'fetch.recurseSubmodules=false',
|
|
756
|
+
'credential.helper=',
|
|
757
|
+
'core.askPass=',
|
|
758
|
+
'init.defaultBranch=main',
|
|
759
|
+
'advice.detachedHead=false',
|
|
760
|
+
];
|
|
761
|
+
const proxy = parsed !== undefined && (transport === 'https' || transport === 'http') ? proxyFor(parsed) : undefined;
|
|
762
|
+
// The route Harness Forge chose; through the child's environment, so a proxy password never sits in its arguments.
|
|
763
|
+
const env = {};
|
|
764
|
+
const extra = [];
|
|
765
|
+
if (transport === 'https' || transport === 'http') {
|
|
766
|
+
options.push('http.followRedirects=false');
|
|
767
|
+
const version = await this.version();
|
|
768
|
+
if (version !== undefined && (version[0] > 2 || (version[0] === 2 && version[1] >= 31))) {
|
|
769
|
+
extra.push('--config-env=http.proxy=HF_GIT_PROXY');
|
|
770
|
+
env['HF_GIT_PROXY'] = proxy?.href ?? '';
|
|
771
|
+
}
|
|
772
|
+
else if (proxy === undefined || (proxy.username.length === 0 && proxy.password.length === 0)) {
|
|
773
|
+
options.push(`http.proxy=${proxy?.href ?? ''}`);
|
|
774
|
+
}
|
|
775
|
+
else {
|
|
776
|
+
throw new HarnessError('fetch-failed', 'git older than 2.31 cannot be given a proxy password safely', { suggestion: 'Update git to 2.31 or later.' });
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
if (context.trust === 'marketplace') {
|
|
780
|
+
if (parsed === undefined || parsed.username.length > 0 || parsed.password.length > 0)
|
|
781
|
+
throw new HarnessError('unsupported-source', 'a marketplace entry may not carry credentials in its URL');
|
|
782
|
+
const host = parsed.hostname.replace(/^\[|\]$/gu, '');
|
|
783
|
+
if (proxy === undefined) {
|
|
784
|
+
const addresses = await this.addresses(host, context, true);
|
|
785
|
+
// curl connects to the addresses checked, not to a second answer from the resolver.
|
|
786
|
+
if (isIP(host) === 0)
|
|
787
|
+
options.push(`http.curloptResolve=${host}:${parsed.port || '443'}:${addresses.map(address => isIP(address) === 6 ? `[${address}]` : address).join(',')}`);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
return { options: [...options.flatMap(option => ['-c', option]), ...extra], url, env };
|
|
791
|
+
}
|
|
792
|
+
runGit(options, args, context, step) {
|
|
793
|
+
return this.run(this.deps.git, 'git', [...options, ...args], context, { cwd: step.cwd ?? this.isolation().empty, ...(step.watch !== undefined ? { watch: step.watch } : {}), env: { ...this.gitEnv(), ...step.env }, stepMs: step.stepMs ?? this.limits.fetchMs, what: step.what });
|
|
794
|
+
}
|
|
795
|
+
/** The commit a git source points at now: its pinned SHA, else its ref (or default branch) on the remote. */
|
|
796
|
+
async latest(spec, context = this.context('user')) {
|
|
797
|
+
if (spec.sha !== undefined) {
|
|
798
|
+
if (!isFullSha(spec.sha))
|
|
799
|
+
throw new HarnessError('unsupported-source', `not a full commit SHA: ${spec.sha}`);
|
|
800
|
+
return spec.sha;
|
|
801
|
+
}
|
|
802
|
+
if (spec.ref !== undefined && !isValidRef(spec.ref))
|
|
803
|
+
throw new HarnessError('unsupported-source', `not a branch or tag name git accepts: ${spec.ref}`);
|
|
804
|
+
const git = await this.gitFor(spec.url, context);
|
|
805
|
+
if (git.use) {
|
|
806
|
+
const { options, url, env } = await this.gitOptions(spec.url, context);
|
|
807
|
+
let out;
|
|
808
|
+
try {
|
|
809
|
+
out = await this.runGit(options, ['ls-remote', '--', url, ...(spec.ref !== undefined ? [spec.ref, `refs/tags/${spec.ref}^{}`] : ['HEAD'])], context, { stepMs: this.limits.lookupMs, what: `reading ${shown(spec.url)}`, env });
|
|
810
|
+
}
|
|
811
|
+
catch (error) {
|
|
812
|
+
if (error instanceof HarnessError)
|
|
813
|
+
throw error;
|
|
814
|
+
throw new HarnessError('fetch-failed', `cannot read ${shown(spec.url)}: ${scrub(messageOf(error))}`, { cause: error, suggestion: 'Check the URL, that the repository is public, and the network connection.' });
|
|
815
|
+
}
|
|
816
|
+
const lines = out.split(/\r?\n/u).map(line => line.split(/\s+/u)).filter(([sha]) => sha !== undefined && isFullSha(sha));
|
|
817
|
+
// An annotated tag's commit is its peeled line.
|
|
818
|
+
const found = lines.find(([, ref]) => ref?.endsWith('^{}') === true) ?? lines[0];
|
|
819
|
+
if (found?.[0] === undefined)
|
|
820
|
+
throw new HarnessError('fetch-failed', `${shown(spec.url)} has no ${spec.ref ?? 'default branch'}`);
|
|
821
|
+
return found[0];
|
|
822
|
+
}
|
|
823
|
+
if (spec.github !== undefined) {
|
|
824
|
+
const text = (await this.download(githubCommitApi(spec.github.owner, spec.github.repo, spec.ref), 4096, this.limits.lookupMs, context, { accept: 'application/vnd.github.sha' })).toString('utf8').trim();
|
|
825
|
+
if (!isFullSha(text))
|
|
826
|
+
throw new HarnessError('fetch-failed', `GitHub did not name the commit of ${spec.github.owner}/${spec.github.repo}${spec.ref !== undefined ? `#${spec.ref}` : ''}`);
|
|
827
|
+
return text;
|
|
828
|
+
}
|
|
829
|
+
throw this.gitRequired(spec, git.why);
|
|
830
|
+
}
|
|
831
|
+
gitRequired(spec, why = 'git is not installed') {
|
|
832
|
+
return why === 'git is not installed'
|
|
833
|
+
? new HarnessError('fetch-failed', `git is needed to fetch ${shown(spec.url)}`, { suggestion: 'Install git (https://git-scm.com/downloads); without it Harness Forge can fetch from GitHub only.' })
|
|
834
|
+
: new HarnessError('fetch-failed', `Harness Forge does not fetch ${shown(spec.url)} for a marketplace: ${why}`, { suggestion: why.startsWith('behind a proxy') ? `If you trust it, paste ${shown(spec.url)} yourself.` : 'Update git to 2.37 or later, or paste the repository yourself.' });
|
|
835
|
+
}
|
|
836
|
+
/** Where checkouts of one source (URL and directory) are kept. */
|
|
837
|
+
cacheDir(spec) {
|
|
838
|
+
return join(this.root, 'cache', 'git', cacheKey(spec.url, spec.subpath ?? ''));
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Check out a git source at `sha` (else at what it points at now) under the
|
|
842
|
+
* cache, reusing a checkout of that commit. A checkout is never replaced:
|
|
843
|
+
* one is made in a directory of its own and renamed into place; old ones are
|
|
844
|
+
* collected by the service between operations.
|
|
845
|
+
*/
|
|
846
|
+
async checkout(spec, context = this.context('user'), sha) {
|
|
847
|
+
const wanted = sha ?? spec.sha;
|
|
848
|
+
if (wanted !== undefined && !isFullSha(wanted))
|
|
849
|
+
throw new HarnessError('unsupported-source', `not a full commit SHA: ${wanted}`);
|
|
850
|
+
if (spec.ref !== undefined && !isValidRef(spec.ref))
|
|
851
|
+
throw new HarnessError('unsupported-source', `not a branch or tag name git accepts: ${spec.ref}`);
|
|
852
|
+
const keyDir = this.cacheDir(spec);
|
|
853
|
+
if (wanted !== undefined && existsSync(join(keyDir, wanted)))
|
|
854
|
+
return { dir: join(keyDir, wanted), sha: wanted };
|
|
855
|
+
const git = await this.gitFor(spec.url, context);
|
|
856
|
+
if (!git.use && spec.github === undefined)
|
|
857
|
+
throw this.gitRequired(spec, git.why);
|
|
858
|
+
const tmp = temporary(keyDir);
|
|
859
|
+
try {
|
|
860
|
+
const resolved = git.use ? await this.gitCheckout(spec, wanted, tmp, context) : await this.tarballCheckout(spec, wanted, tmp, context);
|
|
861
|
+
if (treeSize(tmp, this.limits.tree).over)
|
|
862
|
+
throw tooLargeError(spec.url, this.limits.tree);
|
|
863
|
+
const dir = join(keyDir, resolved);
|
|
864
|
+
if (existsSync(dir))
|
|
865
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
866
|
+
else
|
|
867
|
+
renameSync(tmp, dir);
|
|
868
|
+
return { dir, sha: resolved };
|
|
869
|
+
}
|
|
870
|
+
catch (error) {
|
|
871
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
872
|
+
throw error;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
/** Fetch one commit (depth 1, no blobs but those checked out, only the plugin's directory) into an empty repository. */
|
|
876
|
+
async gitCheckout(spec, sha, dir, context) {
|
|
877
|
+
const { options, url, env } = await this.gitOptions(spec.url, context);
|
|
878
|
+
const what = `fetching ${shown(spec.url)}`;
|
|
879
|
+
const git = (args, stepMs) => this.runGit(options, args, context, { cwd: dir, watch: dir, what, env, ...(stepMs !== undefined ? { stepMs } : {}) });
|
|
880
|
+
mkdirSync(dir, { recursive: true });
|
|
881
|
+
try {
|
|
882
|
+
await git(['init', '--quiet', `--template=${this.isolation().template}`], this.limits.lookupMs);
|
|
883
|
+
await git(['remote', 'add', '--', 'origin', url], this.limits.lookupMs);
|
|
884
|
+
if (spec.subpath !== undefined)
|
|
885
|
+
await git(['sparse-checkout', 'set', '--', spec.subpath], this.limits.lookupMs);
|
|
886
|
+
const target = sha ?? spec.ref ?? 'HEAD';
|
|
887
|
+
try {
|
|
888
|
+
await git(['fetch', '--quiet', '--depth=1', '--filter=blob:none', '--no-tags', '--', 'origin', target]);
|
|
889
|
+
}
|
|
890
|
+
catch (error) {
|
|
891
|
+
if (error instanceof HarnessError || sha === undefined)
|
|
892
|
+
throw error;
|
|
893
|
+
// Claude Code names AWS CodeCommit as a server that does not serve a commit by SHA; fetching its whole history instead is unbounded.
|
|
894
|
+
throw new HarnessError('fetch-failed', `${shown(spec.url)} does not serve commit ${sha.slice(0, 12)} on its own: ${scrub(messageOf(error))}`, { cause: error, suggestion: 'The server must allow fetching a commit by its SHA (GitHub, GitLab and Bitbucket do); Harness Forge does not download a whole history to find it.' });
|
|
895
|
+
}
|
|
896
|
+
const head = (await git(['rev-parse', '--verify', '--end-of-options', 'FETCH_HEAD^{commit}'], this.limits.lookupMs)).trim();
|
|
897
|
+
if (!isFullSha(head))
|
|
898
|
+
throw new HarnessError('fetch-failed', `git did not name the commit fetched from ${shown(spec.url)}`);
|
|
899
|
+
if (sha !== undefined && head !== sha)
|
|
900
|
+
throw new HarnessError('fetch-failed', `${shown(spec.url)} answered commit ${head.slice(0, 12)} for ${sha.slice(0, 12)}`);
|
|
901
|
+
await git(['checkout', '--quiet', '--detach', head]);
|
|
902
|
+
rmSync(join(dir, '.git'), { recursive: true, force: true });
|
|
903
|
+
return head;
|
|
904
|
+
}
|
|
905
|
+
catch (error) {
|
|
906
|
+
if (error instanceof HarnessError)
|
|
907
|
+
throw error;
|
|
908
|
+
throw new HarnessError('fetch-failed', `git could not fetch ${shown(spec.url)}${spec.ref !== undefined ? ` (${spec.ref})` : ''}: ${scrub(messageOf(error))}`, { cause: error, suggestion: 'Check the URL and ref, that the repository is public, and the network connection.' });
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
async tarballCheckout(spec, sha, dir, context) {
|
|
912
|
+
const { owner, repo } = spec.github;
|
|
913
|
+
const archive = await this.download(githubTarball(owner, repo, sha ?? spec.ref ?? 'HEAD'), this.limits.archiveBytes, this.limits.fetchMs, context);
|
|
914
|
+
const { commit } = await extractTarGz(archive, dir, { strip: 1, limits: this.limits.tree, signal: context.signal });
|
|
915
|
+
if (sha !== undefined && commit !== undefined && commit !== sha)
|
|
916
|
+
throw new HarnessError('fetch-failed', `the GitHub archive of ${owner}/${repo} is commit ${commit.slice(0, 12)}, not ${sha.slice(0, 12)}`);
|
|
917
|
+
const resolved = commit ?? sha;
|
|
918
|
+
if (resolved === undefined)
|
|
919
|
+
throw new HarnessError('fetch-failed', `the GitHub archive of ${owner}/${repo} does not name its commit`);
|
|
920
|
+
return resolved;
|
|
921
|
+
}
|
|
922
|
+
// --- npm ------------------------------------------------------------------
|
|
923
|
+
/**
|
|
924
|
+
* The registry npm is configured with, read without running npm:
|
|
925
|
+
* `npm_config_registry`, else the `registry=` line of the user's `.npmrc`,
|
|
926
|
+
* else npm's own. Per-scope registries and auth are not read.
|
|
927
|
+
*/
|
|
928
|
+
configuredRegistry() {
|
|
929
|
+
const fromEnv = process.env['npm_config_registry'] ?? process.env['NPM_CONFIG_REGISTRY'];
|
|
930
|
+
if (fromEnv !== undefined && normalizeRegistry(fromEnv) !== undefined)
|
|
931
|
+
return normalizeRegistry(fromEnv);
|
|
932
|
+
try {
|
|
933
|
+
const npmrc = readFileSync(process.env['npm_config_userconfig'] ?? join(homedir(), '.npmrc'), 'utf8');
|
|
934
|
+
const line = /^[ \t]*registry[ \t]*=[ \t]*(\S+)[ \t]*\r?$/mu.exec(npmrc)?.[1];
|
|
935
|
+
if (line !== undefined && !line.includes('${') && normalizeRegistry(line) !== undefined)
|
|
936
|
+
return normalizeRegistry(line);
|
|
937
|
+
}
|
|
938
|
+
catch {
|
|
939
|
+
// No .npmrc.
|
|
940
|
+
}
|
|
941
|
+
return NPM_REGISTRY;
|
|
942
|
+
}
|
|
943
|
+
/** The registry an npm source is fetched from: the configured one, or one a marketplace names when it is npm's own or the configured one. */
|
|
944
|
+
registryOf(spec) {
|
|
945
|
+
const configured = this.configuredRegistry();
|
|
946
|
+
if (spec.registry === undefined)
|
|
947
|
+
return configured;
|
|
948
|
+
const named = normalizeRegistry(spec.registry);
|
|
949
|
+
if (named !== undefined && (named === NPM_REGISTRY || named === configured))
|
|
950
|
+
return named;
|
|
951
|
+
throw new HarnessError('unsupported-source', `the marketplace names the npm registry ${spec.registry}; Harness Forge fetches only from npm's own registry or the one npm is configured with (${configured})`);
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* The exact version an npm source names now (an exact version, or a
|
|
955
|
+
* dist-tag such as `latest`; not a range), with its tarball and integrity,
|
|
956
|
+
* read from the registry's document by Harness Forge itself.
|
|
957
|
+
*/
|
|
958
|
+
async npmLatest(spec, context = this.context('user')) {
|
|
959
|
+
const wanted = spec.version ?? 'latest';
|
|
960
|
+
if (!EXACT_VERSION.test(wanted) && !DIST_TAG.test(wanted))
|
|
961
|
+
throw new HarnessError('unsupported-source', `Harness Forge installs an exact npm version or a tag such as latest, not a range: ${spec.package}@${wanted}`, { suggestion: `Name an exact version, such as ${spec.package}@1.2.3.` });
|
|
962
|
+
const registry = this.registryOf(spec);
|
|
963
|
+
// The registry is the person's choice (or npm's own); what it redirects to is checked.
|
|
964
|
+
const registryContext = RemoteFetcher.as(context, 'user');
|
|
965
|
+
const document = await this.json(`${registry}${spec.package.replace('/', '%2f')}`, registryContext, PACKUMENT_BYTES, 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8');
|
|
966
|
+
const tags = isRecord(document['dist-tags']) ? document['dist-tags'] : {};
|
|
967
|
+
const version = EXACT_VERSION.test(wanted) ? wanted : tags[wanted];
|
|
968
|
+
const entry = typeof version === 'string' && isRecord(document['versions']) ? document['versions'][version] : undefined;
|
|
969
|
+
if (typeof version !== 'string' || !EXACT_VERSION.test(version) || !isRecord(entry))
|
|
970
|
+
throw new HarnessError('fetch-failed', `${registry} has no version of ${spec.package} matching ${wanted}`);
|
|
971
|
+
const dist = isRecord(entry['dist']) ? entry['dist'] : {};
|
|
972
|
+
const tarball = typeof dist['tarball'] === 'string' ? dist['tarball'] : '';
|
|
973
|
+
const integrity = typeof dist['integrity'] === 'string' ? dist['integrity'] : '';
|
|
974
|
+
if (entry['name'] !== spec.package || entry['version'] !== version)
|
|
975
|
+
throw new HarnessError('manifest-invalid', `${registry} describes ${spec.package}@${version} as another package`);
|
|
976
|
+
let origin;
|
|
977
|
+
try {
|
|
978
|
+
origin = new URL(tarball).origin;
|
|
979
|
+
}
|
|
980
|
+
catch {
|
|
981
|
+
origin = undefined;
|
|
982
|
+
}
|
|
983
|
+
if (origin !== new URL(registry).origin)
|
|
984
|
+
throw new HarnessError('fetch-failed', `the tarball of ${spec.package}@${version} is not on ${registry}: ${shown(tarball)}`);
|
|
985
|
+
if (!SHA512.test(integrity))
|
|
986
|
+
throw new HarnessError('fetch-failed', `${registry} gives no sha512 integrity for ${spec.package}@${version}`);
|
|
987
|
+
return { name: spec.package, version, integrity, registry, tarball };
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Download one package version's tarball (nothing else), check it against
|
|
991
|
+
* its integrity, and unpack it to `<dest>/package`. npm does not run.
|
|
992
|
+
* @returns the package directory and its `package.json`.
|
|
993
|
+
*/
|
|
994
|
+
async npmFetch(pkg, dest, context) {
|
|
995
|
+
const bytes = await this.download(pkg.tarball, this.limits.archiveBytes, this.limits.fetchMs, RemoteFetcher.as(context, 'user'));
|
|
996
|
+
if (`sha512-${createHash('sha512').update(bytes).digest('base64')}` !== pkg.integrity)
|
|
997
|
+
throw new HarnessError('fetch-failed', `${pkg.name}@${pkg.version} does not match the integrity its registry gives`);
|
|
998
|
+
const dir = join(dest, 'package');
|
|
999
|
+
await extractTarGz(bytes, dir, { strip: 1, limits: PLUGIN_LIMITS, signal: context.signal });
|
|
1000
|
+
let manifest;
|
|
1001
|
+
try {
|
|
1002
|
+
manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
1003
|
+
}
|
|
1004
|
+
catch {
|
|
1005
|
+
manifest = undefined;
|
|
1006
|
+
}
|
|
1007
|
+
if (!isRecord(manifest))
|
|
1008
|
+
throw new HarnessError('manifest-invalid', `${pkg.name}@${pkg.version} has no package.json`);
|
|
1009
|
+
if (manifest['name'] !== pkg.name || manifest['version'] !== pkg.version)
|
|
1010
|
+
throw new HarnessError('manifest-invalid', `the tarball of ${pkg.name}@${pkg.version} is ${String(manifest['name'])}@${String(manifest['version'])}`);
|
|
1011
|
+
return { dir, manifest };
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Install a confirmed package's dependencies into `prefix` (its own
|
|
1015
|
+
* `package.json` naming only them). The person confirmed the plugin, so its
|
|
1016
|
+
* registry dependencies are trusted, as OpenCode installs plugins; still,
|
|
1017
|
+
* install scripts do not run, npm's cache is inside `prefix` (in the size
|
|
1018
|
+
* bound), and the resolved tree is refused when any package in it is not a
|
|
1019
|
+
* tarball from the registry with an integrity.
|
|
1020
|
+
*/
|
|
1021
|
+
async npmDependencies(prefix, dependencies, registry, context) {
|
|
1022
|
+
writeJson(join(prefix, 'package.json'), { name: 'harness-forge-remote', private: true, dependencies: dependencies.dependencies, optionalDependencies: dependencies.optionalDependencies });
|
|
1023
|
+
if (Object.keys(dependencies.dependencies).length + Object.keys(dependencies.optionalDependencies).length === 0)
|
|
1024
|
+
return;
|
|
1025
|
+
const cache = join(prefix, '.npm-cache');
|
|
1026
|
+
// The lockfile version is forced, so a person's npmrc cannot pick one the audit cannot read.
|
|
1027
|
+
const args = ['--ignore-scripts', '--no-audit', '--no-fund', `--lockfile-version=${String(NPM_LOCKFILE_VERSION)}`, `--registry=${registry}`, `--cache=${cache}`];
|
|
1028
|
+
const step = { cwd: prefix, watch: prefix, stepMs: this.limits.fetchMs, what: 'installing the dependencies' };
|
|
1029
|
+
try {
|
|
1030
|
+
await this.run(this.deps.npm, 'npm', ['install', '--package-lock-only', ...args], context, step);
|
|
1031
|
+
refuseForeignPackages(JSON.parse(readFileSync(join(prefix, 'package-lock.json'), 'utf8')), registry);
|
|
1032
|
+
await this.run(this.deps.npm, 'npm', ['ci', '--omit=dev', ...args], context, step);
|
|
1033
|
+
}
|
|
1034
|
+
catch (error) {
|
|
1035
|
+
throw error instanceof HarnessError ? error : npmError('the dependencies', error);
|
|
1036
|
+
}
|
|
1037
|
+
finally {
|
|
1038
|
+
rmSync(cache, { recursive: true, force: true });
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
// --- archives ---------------------------------------------------------------
|
|
1042
|
+
/** Download and unpack a zip `archive` source into `dest`; its sha256 is the revision. */
|
|
1043
|
+
async archive(spec, dest, context) {
|
|
1044
|
+
const bytes = await this.download(spec.url, this.limits.archiveBytes, this.limits.fetchMs, context);
|
|
1045
|
+
const digest = createHash('sha256').update(bytes).digest('hex');
|
|
1046
|
+
if (spec.sha256 !== undefined && spec.sha256 !== digest)
|
|
1047
|
+
throw new HarnessError('fetch-failed', `${shown(spec.url)} does not match its sha256 pin (got ${digest})`);
|
|
1048
|
+
await extractZip(bytes, dest, { signal: context.signal });
|
|
1049
|
+
return { root: zipRoot(dest), digest };
|
|
1050
|
+
}
|
|
1051
|
+
/** A directory inside `root`, or a failure naming the path that leaves it. */
|
|
1052
|
+
static inside(root, path) {
|
|
1053
|
+
const target = path === undefined ? resolve(root) : resolve(root, path);
|
|
1054
|
+
if (target !== resolve(root) && !isInside(root, target))
|
|
1055
|
+
throw new HarnessError('path-escape', `the plugin path leaves its repository: ${path ?? ''}`);
|
|
1056
|
+
if (!existsSync(target))
|
|
1057
|
+
throw new HarnessError('manifest-not-found', `the repository has no ${path ?? ''} directory`);
|
|
1058
|
+
// Reached through no link: its real path is where its path says.
|
|
1059
|
+
if (!lstatSync(target).isDirectory() || relative(realpathSync(root), realpathSync(target)) !== relative(resolve(root), target))
|
|
1060
|
+
throw new HarnessError('path-escape', `the plugin path is a link or reached through one: ${path ?? '.'}`);
|
|
1061
|
+
refuseLinkedManifests(target);
|
|
1062
|
+
return target;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
function isRecord(value) {
|
|
1066
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* The lockfile version npm is told to write: 3, the default of npm 7 and
|
|
1070
|
+
* later, holds only the `packages` map the audit reads (version 1 has none,
|
|
1071
|
+
* so an audit of it would see nothing).
|
|
1072
|
+
*/
|
|
1073
|
+
export const NPM_LOCKFILE_VERSION = 3;
|
|
1074
|
+
/** Lockfile versions with a `packages` map (2 carries it beside version 1's data). */
|
|
1075
|
+
const AUDITED_LOCKFILE_VERSIONS = [2, 3];
|
|
1076
|
+
/**
|
|
1077
|
+
* Refuse a resolved dependency tree with any package that is not a registry
|
|
1078
|
+
* tarball: a link (`file:`, `link:`, `workspace:`), a git or URL source, a
|
|
1079
|
+
* tarball on another origin, or one without an integrity. Bundled packages
|
|
1080
|
+
* come inside a registry tarball; `npm:` aliases resolve to registry tarballs
|
|
1081
|
+
* like any other.
|
|
1082
|
+
*/
|
|
1083
|
+
export function refuseForeignPackages(lock, registry) {
|
|
1084
|
+
const origin = new URL(registry).origin;
|
|
1085
|
+
// Fail closed: a lockfile the audit cannot read is not a tree with nothing in it.
|
|
1086
|
+
if (!AUDITED_LOCKFILE_VERSIONS.includes(lock.lockfileVersion) || !isRecord(lock.packages)) {
|
|
1087
|
+
throw new HarnessError('unsupported-source', `npm wrote a lockfile Harness Forge cannot check (lockfileVersion ${JSON.stringify(lock.lockfileVersion ?? null)}${isRecord(lock.packages) ? '' : ', no packages map'}), so the dependencies are not installed`, { suggestion: `Use npm 7 or later; Harness Forge asks it for lockfile version ${String(NPM_LOCKFILE_VERSION)}.` });
|
|
1088
|
+
}
|
|
1089
|
+
for (const [path, entry] of Object.entries(lock.packages)) {
|
|
1090
|
+
if (path === '' || entry.inBundle === true)
|
|
1091
|
+
continue;
|
|
1092
|
+
const name = path.replace(/^.*node_modules\//u, '');
|
|
1093
|
+
const resolved = typeof entry.resolved === 'string' ? entry.resolved : undefined;
|
|
1094
|
+
let url;
|
|
1095
|
+
try {
|
|
1096
|
+
url = resolved === undefined ? undefined : new URL(resolved);
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
url = undefined;
|
|
1100
|
+
}
|
|
1101
|
+
const fromRegistry = entry.link !== true && url !== undefined && (url.protocol === 'https:' || url.protocol === 'http:') && url.origin === origin && url.pathname.endsWith('.tgz');
|
|
1102
|
+
const pinned = typeof entry.integrity === 'string' && /^sha(?:512|1)-/u.test(entry.integrity);
|
|
1103
|
+
if (!fromRegistry || !pinned) {
|
|
1104
|
+
throw new HarnessError('unsupported-source', `the dependency ${name} would come from ${resolved ?? 'a local folder'}${fromRegistry ? ' without an integrity' : `, not from ${registry}`}; Harness Forge installs dependencies from the registry only`, { suggestion: 'Ask the plugin\'s author to publish that dependency to npm.' });
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* What a package declares to install with it, refused when any of it is not
|
|
1110
|
+
* a registry lookup (git, GitHub, `file:`, `link:`, `workspace:`, a URL).
|
|
1111
|
+
*/
|
|
1112
|
+
export function dependenciesOf(manifest) {
|
|
1113
|
+
const read = (key) => {
|
|
1114
|
+
const value = manifest[key];
|
|
1115
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
1116
|
+
return {};
|
|
1117
|
+
return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === 'string'));
|
|
1118
|
+
};
|
|
1119
|
+
const dependencies = read('dependencies');
|
|
1120
|
+
const optionalDependencies = read('optionalDependencies');
|
|
1121
|
+
const problems = [...Object.entries(dependencies), ...Object.entries(optionalDependencies)].flatMap(([name, spec]) => {
|
|
1122
|
+
const problem = dependencyProblem(name, spec);
|
|
1123
|
+
return problem === undefined ? [] : [problem];
|
|
1124
|
+
});
|
|
1125
|
+
if (problems.length > 0)
|
|
1126
|
+
throw new HarnessError('unsupported-source', `${String(manifest['name'])} cannot be installed: ${problems.join('; ')}`, { suggestion: 'Ask the plugin\'s author to depend on published npm packages only.' });
|
|
1127
|
+
return { dependencies, optionalDependencies };
|
|
1128
|
+
}
|
|
1129
|
+
function npmError(name, error) {
|
|
1130
|
+
if (error.code === 'ENOENT')
|
|
1131
|
+
return new HarnessError('fetch-failed', 'npm is needed to install npm packages', { suggestion: 'Install Node.js with npm (https://nodejs.org).' });
|
|
1132
|
+
return new HarnessError('fetch-failed', `npm could not fetch ${name}: ${messageOf(error)}`, { cause: error, suggestion: 'Check the package name and the network connection.' });
|
|
1133
|
+
}
|