@zvada/agent-server 0.3.23 → 0.3.25
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/CHANGELOG.md +64 -0
- package/README.md +14 -5
- package/dist/accounts/chatgpt.js +144 -0
- package/dist/accounts/check.js +71 -0
- package/dist/accounts/claude.js +80 -0
- package/dist/accounts/endpoint.js +104 -0
- package/dist/accounts/http.js +58 -0
- package/dist/accounts/index.js +9 -0
- package/dist/client/client.js +745 -0
- package/dist/client/connection.js +338 -0
- package/dist/client/history.js +49 -0
- package/dist/client/index.js +6 -0
- package/dist/client/listeners.js +19 -0
- package/dist/client/logins.js +92 -0
- package/dist/client/rpc.js +105 -0
- package/dist/client/streams.js +432 -0
- package/dist/client/transports.js +118 -0
- package/dist/client/turns.js +122 -0
- package/dist/core/agents/acp/acp-agent.js +425 -0
- package/dist/core/agents/acp/adapter.js +231 -0
- package/dist/core/agents/acp/client.js +222 -0
- package/dist/core/agents/acp/known-agents.js +57 -0
- package/dist/core/agents/acp/mappings.js +164 -0
- package/dist/core/agents/acp/requests.js +79 -0
- package/dist/core/agents/attachments.js +14 -0
- package/dist/core/agents/base.js +64 -0
- package/dist/core/agents/claude-code/adapter.js +474 -0
- package/dist/core/agents/claude-code/approvals.js +245 -0
- package/dist/core/agents/claude-code/claude-agent.js +319 -0
- package/dist/core/agents/claude-code/credentials.js +142 -0
- package/dist/core/agents/claude-code/events.js +11 -0
- package/dist/core/agents/claude-code/login.js +217 -0
- package/dist/core/agents/claude-code/mcp.js +181 -0
- package/dist/core/agents/claude-code/models.js +74 -0
- package/dist/core/agents/claude-code/options.js +240 -0
- package/dist/core/agents/claude-code/outcome.js +204 -0
- package/dist/core/agents/claude-code/results.js +58 -0
- package/dist/core/agents/claude-code/sdk-pair.js +59 -0
- package/dist/core/agents/claude-code/session.js +593 -0
- package/dist/core/agents/claude-code/spawn.js +125 -0
- package/dist/core/agents/claude-code/spend.js +118 -0
- package/dist/core/agents/claude-code/tools.js +131 -0
- package/dist/core/agents/claude-code/turn-usage.js +121 -0
- package/dist/core/agents/claude-code/turn.js +199 -0
- package/dist/core/agents/codex-app-server/adapter.js +463 -0
- package/dist/core/agents/codex-app-server/client.js +338 -0
- package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
- package/dist/core/agents/codex-app-server/commands.js +184 -0
- package/dist/core/agents/codex-app-server/credentials.js +92 -0
- package/dist/core/agents/codex-app-server/effort.js +13 -0
- package/dist/core/agents/codex-app-server/events.js +18 -0
- package/dist/core/agents/codex-app-server/homes.js +118 -0
- package/dist/core/agents/codex-app-server/input.js +52 -0
- package/dist/core/agents/codex-app-server/items.js +307 -0
- package/dist/core/agents/codex-app-server/login.js +183 -0
- package/dist/core/agents/codex-app-server/mcp.js +323 -0
- package/dist/core/agents/codex-app-server/models.js +160 -0
- package/dist/core/agents/codex-app-server/options.js +155 -0
- package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
- package/dist/core/agents/codex-app-server/protocol.js +38 -0
- package/dist/core/agents/codex-app-server/requests.js +250 -0
- package/dist/core/agents/codex-app-server/session.js +278 -0
- package/dist/core/agents/codex-app-server/subagents.js +260 -0
- package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
- package/dist/core/agents/codex-app-server/turn-items.js +69 -0
- package/dist/core/agents/codex-app-server/turn.js +448 -0
- package/dist/core/agents/codex-app-server/user-login.js +78 -0
- package/dist/core/agents/config-fingerprint.js +10 -0
- package/dist/core/agents/credentials.js +71 -0
- package/dist/core/agents/diffs.js +27 -0
- package/dist/core/agents/elicitation.js +42 -0
- package/dist/core/agents/inherit-config.js +5 -0
- package/dist/core/agents/login.js +56 -0
- package/dist/core/agents/mcp-config.js +109 -0
- package/dist/core/agents/plan.js +6 -0
- package/dist/core/agents/process-pool.js +307 -0
- package/dist/core/agents/registry.js +49 -0
- package/dist/core/agents/scripted/adapter.js +86 -0
- package/dist/core/agents/scripted/mcp-call.js +74 -0
- package/dist/core/agents/scripted/scripted-agent.js +331 -0
- package/dist/core/agents/scripted/scripts.js +154 -0
- package/dist/core/agents/scripted/steps.js +87 -0
- package/dist/core/agents/session-agent.js +209 -0
- package/dist/core/agents/stderr-tail.js +71 -0
- package/dist/core/agents/thinking-levels.js +9 -0
- package/dist/core/agents/types.js +1 -0
- package/dist/core/diagnostics.js +23 -0
- package/dist/core/index.js +31 -0
- package/dist/core/presets.js +114 -0
- package/dist/core/processes/identity.js +92 -0
- package/dist/core/processes/lifeline.js +218 -0
- package/dist/core/processes/native-processes.js +299 -0
- package/dist/core/processes/process-table.js +164 -0
- package/dist/core/provision/cache-trust.js +121 -0
- package/dist/core/provision/cache-usage.js +61 -0
- package/dist/core/provision/checksums.js +22 -0
- package/dist/core/provision/extract.js +29 -0
- package/dist/core/provision/index.js +4 -0
- package/dist/core/provision/install-build.js +99 -0
- package/dist/core/provision/npm.js +316 -0
- package/dist/core/provision/pins.js +35 -0
- package/dist/core/provision/platform.js +65 -0
- package/dist/core/provision/provisioner.js +372 -0
- package/dist/core/provision/releases.js +68 -0
- package/dist/core/provision/tools.js +279 -0
- package/dist/core/proxy/anthropic-proxy.js +163 -0
- package/dist/core/proxy/api-key-store.js +30 -0
- package/dist/core/proxy/index.js +3 -0
- package/dist/core/proxy/loopback.js +86 -0
- package/dist/core/runtime/agent-runtime.js +437 -0
- package/dist/core/runtime/event-processor.js +379 -0
- package/dist/core/runtime/event-sink.js +65 -0
- package/dist/core/runtime/harness-clis.js +83 -0
- package/dist/core/runtime/harness-logins.js +313 -0
- package/dist/core/runtime/login-reads.js +71 -0
- package/dist/core/runtime/model-lists.js +160 -0
- package/dist/core/runtime/permission-policy.js +84 -0
- package/dist/core/runtime/request-broker.js +139 -0
- package/dist/core/runtime/steering.js +79 -0
- package/dist/core/runtime/turn-outcome.js +16 -0
- package/dist/core/runtime/turn.js +339 -0
- package/dist/core/utils/bounded.js +13 -0
- package/dist/core/utils/deadline.js +57 -0
- package/dist/core/utils/errors.js +176 -0
- package/dist/core/utils/is-record.js +4 -0
- package/dist/core/utils/loopback.js +11 -0
- package/dist/index.js +4 -0
- package/dist/operator/index.js +10 -0
- package/dist/operator/mcp.js +139 -0
- package/dist/operator/operator.js +499 -0
- package/dist/operator/render.js +408 -0
- package/dist/operator/view.js +35 -0
- package/dist/protocol/account.js +96 -0
- package/dist/protocol/async-queue.js +65 -0
- package/dist/protocol/auth.js +169 -0
- package/dist/protocol/canonical.js +18 -0
- package/dist/protocol/clis.js +63 -0
- package/dist/protocol/config.js +137 -0
- package/dist/protocol/conversation.js +231 -0
- package/dist/protocol/credentials.js +142 -0
- package/dist/protocol/errors.js +190 -0
- package/dist/protocol/execution.js +28 -0
- package/dist/protocol/factories.js +231 -0
- package/dist/protocol/guards.js +71 -0
- package/dist/protocol/harness.js +93 -0
- package/dist/protocol/history.js +201 -0
- package/dist/protocol/ids.js +37 -0
- package/dist/protocol/index.js +36 -0
- package/dist/protocol/lifecycle.js +562 -0
- package/dist/protocol/meta-keys.js +17 -0
- package/dist/protocol/meta.js +13 -0
- package/dist/protocol/model-catalog.js +223 -0
- package/dist/protocol/models.js +84 -0
- package/dist/protocol/part-input.js +94 -0
- package/dist/protocol/parts.js +166 -0
- package/dist/protocol/plan.js +31 -0
- package/dist/protocol/reduce.js +484 -0
- package/dist/protocol/selectors.js +136 -0
- package/dist/protocol/seq-cursor.js +37 -0
- package/dist/protocol/stop-reasons.js +41 -0
- package/dist/protocol/thinking.js +31 -0
- package/dist/protocol/time.js +21 -0
- package/dist/protocol/tokens.js +57 -0
- package/dist/protocol/tool-closure.js +70 -0
- package/dist/protocol/tool-state.js +153 -0
- package/dist/protocol/verify.js +467 -0
- package/dist/protocol/vocabulary.js +27 -0
- package/dist/protocol/wire-api.js +94 -0
- package/dist/protocol/wire.js +669 -0
- package/dist/server/acp/binding.js +251 -0
- package/dist/server/acp/session-records.js +53 -0
- package/dist/server/acp/translate.js +401 -0
- package/dist/server/agent-server.js +338 -0
- package/dist/server/bin.js +492 -0
- package/dist/server/feedback.js +216 -0
- package/dist/server/history.js +123 -0
- package/dist/server/index.js +8 -0
- package/dist/server/install.js +171 -0
- package/dist/server/open-parts.js +87 -0
- package/dist/server/routes.js +292 -0
- package/dist/server/secrets.js +19 -0
- package/dist/server/session-gate.js +54 -0
- package/dist/server/session-log.js +66 -0
- package/dist/server/session-store.js +243 -0
- package/dist/server/subscriptions.js +189 -0
- package/dist/server/transports.js +214 -0
- package/dist/server/wire-error.js +26 -0
- package/dist/sync/event-log.js +89 -0
- package/dist/sync/fit.js +202 -0
- package/dist/sync/history-reader.js +33 -0
- package/dist/sync/history-sqlite.js +281 -0
- package/dist/sync/history.js +163 -0
- package/dist/sync/index.js +5 -0
- package/dist/sync/journal-sqlite.js +316 -0
- package/dist/sync/journal.js +10 -0
- package/dist/sync/live-tails.js +85 -0
- package/dist/sync/node-sqlite.js +27 -0
- package/dist/sync/projection.js +32 -0
- package/dist/sync/recovery.js +117 -0
- package/dist/sync/retry.js +45 -0
- package/dist/sync/schema.js +73 -0
- package/dist/sync/sql.js +94 -0
- package/dist/sync/sqlite-file.js +31 -0
- package/dist/sync/sqlite.js +18 -0
- package/dist/sync/worker.js +212 -0
- package/dist/types/client/client.d.ts +6 -1
- package/dist/types/client/client.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
- package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/options.d.ts +28 -11
- package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
- package/dist/types/core/agents/claude-code/session.d.ts +8 -0
- package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
- package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
- package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
- package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
- package/dist/types/core/agents/process-pool.d.ts +8 -0
- package/dist/types/core/agents/process-pool.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
- package/dist/types/core/agents/scripted/steps.d.ts +1 -1
- package/dist/types/core/presets.d.ts +2 -2
- package/dist/types/core/presets.d.ts.map +1 -1
- package/dist/types/core/processes/identity.d.ts.map +1 -1
- package/dist/types/core/processes/lifeline.d.ts.map +1 -1
- package/dist/types/core/processes/process-table.d.ts.map +1 -1
- package/dist/types/core/provision/extract.d.ts.map +1 -1
- package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
- package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/types/core/runtime/turn.d.ts +12 -7
- package/dist/types/core/runtime/turn.d.ts.map +1 -1
- package/dist/types/protocol/clis.d.ts +3 -3
- package/dist/types/protocol/conversation.d.ts +6 -6
- package/dist/types/protocol/credentials.d.ts +13 -1
- package/dist/types/protocol/credentials.d.ts.map +1 -1
- package/dist/types/protocol/errors.d.ts +6 -4
- package/dist/types/protocol/errors.d.ts.map +1 -1
- package/dist/types/protocol/lifecycle.d.ts +4 -4
- package/dist/types/protocol/wire-api.d.ts +12 -12
- package/dist/types/protocol/wire.d.ts +8 -8
- package/dist/types/server/bin.d.ts +3 -0
- package/dist/types/server/bin.d.ts.map +1 -0
- package/dist/types/server/routes.d.ts.map +1 -1
- package/dist/types/server/transports.d.ts +2 -1
- package/dist/types/server/transports.d.ts.map +1 -1
- package/dist/types/sync/node-sqlite.d.ts +4 -1
- package/dist/types/sync/node-sqlite.d.ts.map +1 -1
- package/docs/consuming.md +56 -7
- package/docs/deploy.md +35 -0
- package/docs/harnesses.md +30 -5
- package/package.json +43 -18
- package/src/client/client.ts +114 -44
- package/src/core/agents/claude-code/approvals.ts +5 -1
- package/src/core/agents/claude-code/claude-agent.ts +32 -5
- package/src/core/agents/claude-code/options.ts +28 -11
- package/src/core/agents/claude-code/session.ts +13 -0
- package/src/core/agents/codex-app-server/homes.ts +11 -2
- package/src/core/agents/codex-app-server/login.ts +30 -0
- package/src/core/agents/codex-app-server/requests.ts +7 -6
- package/src/core/agents/codex-app-server/session.ts +11 -2
- package/src/core/agents/process-pool.ts +30 -4
- package/src/core/agents/scripted/scripted-agent.ts +2 -1
- package/src/core/agents/scripted/steps.ts +1 -1
- package/src/core/presets.ts +3 -2
- package/src/core/processes/identity.ts +1 -0
- package/src/core/processes/lifeline.ts +10 -1
- package/src/core/processes/process-table.ts +1 -0
- package/src/core/provision/extract.ts +1 -0
- package/src/core/runtime/agent-runtime.ts +6 -3
- package/src/core/runtime/turn.ts +21 -9
- package/src/protocol/credentials.ts +19 -5
- package/src/protocol/errors.ts +12 -3
- package/src/server/bin.ts +25 -10
- package/src/server/routes.ts +3 -2
- package/src/server/transports.ts +6 -1
- package/src/sync/node-sqlite.ts +19 -3
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
|
|
2
|
+
import { dirname, isAbsolute, join, parse, relative, sep } from "node:path";
|
|
3
|
+
import { CliProvisionError } from "../utils/errors.js";
|
|
4
|
+
/*
|
|
5
|
+
* Trust checks for the managed CLI cache: a binary the engine spawns must sit
|
|
6
|
+
* in directories only this user (or root) can write, reached without a
|
|
7
|
+
* symlink an outsider planted, and be a regular file nobody else can write.
|
|
8
|
+
*/
|
|
9
|
+
function refuseCache(path, reason) {
|
|
10
|
+
throw new CliProvisionError(`Untrusted CLI cache path ${path}: ${reason} — refusing to use it`);
|
|
11
|
+
}
|
|
12
|
+
function trustedOwner(path, stat, ownOnly = false) {
|
|
13
|
+
if (typeof process.getuid !== "function")
|
|
14
|
+
return;
|
|
15
|
+
const uid = process.getuid();
|
|
16
|
+
if (stat.uid !== uid && (ownOnly || stat.uid !== 0))
|
|
17
|
+
refuseCache(path, `owned by uid ${stat.uid}, expected ${uid}${ownOnly ? "" : " or root"}`);
|
|
18
|
+
}
|
|
19
|
+
function privateDirectory(path, stat, allowSticky = false) {
|
|
20
|
+
if (!stat.isDirectory())
|
|
21
|
+
refuseCache(path, "not a directory (planted symlink?)");
|
|
22
|
+
trustedOwner(path, stat);
|
|
23
|
+
if (typeof process.getuid === "function" &&
|
|
24
|
+
stat.mode & 0o022 &&
|
|
25
|
+
!(allowSticky && stat.mode & 0o1000)) {
|
|
26
|
+
refuseCache(path, "writable by other users");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function createDirectory(path) {
|
|
30
|
+
try {
|
|
31
|
+
mkdirSync(path, { mode: 0o700 });
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code !== "EEXIST")
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Check each parent before creating its child; trusted sticky parents permit /tmp. */
|
|
39
|
+
export function trustedCacheDirectory(path, ownLeaf) {
|
|
40
|
+
const root = parse(path).root;
|
|
41
|
+
let current = root;
|
|
42
|
+
privateDirectory(root, lstatSync(root), true);
|
|
43
|
+
const components = relative(root, path).split(sep).filter(Boolean);
|
|
44
|
+
if (ownLeaf && !components.length)
|
|
45
|
+
refuseCache(path, "filesystem root cannot be a CLI cache");
|
|
46
|
+
for (const [index, component] of components.entries()) {
|
|
47
|
+
const candidate = join(current, component);
|
|
48
|
+
createDirectory(candidate);
|
|
49
|
+
const stat = lstatSync(candidate);
|
|
50
|
+
const leaf = ownLeaf && index === components.length - 1;
|
|
51
|
+
if (stat.isSymbolicLink() && !leaf) {
|
|
52
|
+
trustedOwner(candidate, stat);
|
|
53
|
+
current = trustedCacheDirectory(realpathSync(candidate), false);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (leaf) {
|
|
57
|
+
if (!stat.isDirectory())
|
|
58
|
+
refuseCache(candidate, "not a directory (planted symlink?)");
|
|
59
|
+
trustedOwner(candidate, stat, true);
|
|
60
|
+
if (typeof process.getuid === "function" && (stat.mode & 0o777) !== 0o700)
|
|
61
|
+
chmodSync(candidate, 0o700);
|
|
62
|
+
}
|
|
63
|
+
else
|
|
64
|
+
privateDirectory(candidate, stat, true);
|
|
65
|
+
current = candidate;
|
|
66
|
+
}
|
|
67
|
+
return current;
|
|
68
|
+
}
|
|
69
|
+
/** Managed descendants cannot be aliases or outsider-writable, even under a repaired root. */
|
|
70
|
+
export function managedDirectory(root, path, create) {
|
|
71
|
+
const rel = relative(root, path);
|
|
72
|
+
if (isAbsolute(rel) || rel.split(sep).includes(".."))
|
|
73
|
+
refuseCache(path, "outside the managed root");
|
|
74
|
+
let current = root;
|
|
75
|
+
for (const component of rel.split(sep).filter(Boolean)) {
|
|
76
|
+
current = join(current, component);
|
|
77
|
+
if (create)
|
|
78
|
+
createDirectory(current);
|
|
79
|
+
let stat;
|
|
80
|
+
try {
|
|
81
|
+
stat = lstatSync(current);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (error.code === "ENOENT")
|
|
85
|
+
return false;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
privateDirectory(current, stat);
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
export function trustedBinary(path, stat) {
|
|
93
|
+
if (!stat.isFile())
|
|
94
|
+
refuseCache(path, "not a regular executable file");
|
|
95
|
+
trustedOwner(path, stat);
|
|
96
|
+
if (typeof process.getuid === "function" && stat.mode & 0o022)
|
|
97
|
+
refuseCache(path, "executable writable by other users");
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* The first of `binaries` under a managed `dir` that is a trusted regular
|
|
101
|
+
* file. A symlink here could redirect the spawn — and the post-install
|
|
102
|
+
* `chmod` — at a path outside the tree we verified.
|
|
103
|
+
*/
|
|
104
|
+
export function trustedBinaryIn(root, dir, binaries) {
|
|
105
|
+
for (const candidate of binaries) {
|
|
106
|
+
const path = join(dir, candidate);
|
|
107
|
+
if (!managedDirectory(root, dirname(path), false))
|
|
108
|
+
continue;
|
|
109
|
+
let stat;
|
|
110
|
+
try {
|
|
111
|
+
stat = lstatSync(path);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
trustedBinary(path, stat);
|
|
117
|
+
if (stat.isFile())
|
|
118
|
+
return path;
|
|
119
|
+
}
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { mkdir, readdir, rm, stat, utimes, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
/** Builds unused this long are pruned. */
|
|
4
|
+
const PRUNE_AFTER_MS = 14 * 24 * 60 * 60 * 1000;
|
|
5
|
+
/** What an install that died left in `.tmp`; no live install takes this long. */
|
|
6
|
+
const LEFTOVER_AFTER_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
/** Where the last use of a cached build is recorded: outside the build, which stays as installed. */
|
|
8
|
+
function usedMarker(root, tool, entry) {
|
|
9
|
+
return join(root, ".used", `${tool}-${entry}`);
|
|
10
|
+
}
|
|
11
|
+
/** Record that a cached build was used now. Best effort: a read-only cache still runs. */
|
|
12
|
+
export async function markUsed(root, tool, entry) {
|
|
13
|
+
const marker = usedMarker(root, tool, entry);
|
|
14
|
+
const now = new Date();
|
|
15
|
+
try {
|
|
16
|
+
await utimes(marker, now, now);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
await mkdir(join(root, ".used"), { recursive: true, mode: 0o700 }).catch(() => { });
|
|
20
|
+
await writeFile(marker, "", { mode: 0o600 }).catch(() => { });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
async function mtimeOf(path) {
|
|
24
|
+
return (await stat(path).catch(() => undefined))?.mtimeMs;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Remove the cached builds of `tools` whose recorded last use is 14 days old,
|
|
28
|
+
* never one `keep` names (`<tool>/<entry>`), and what dead installs left in
|
|
29
|
+
* `.tmp`. Several products may share one cache with their own pins: each
|
|
30
|
+
* keeps its builds by using them. A build no use was ever recorded for was
|
|
31
|
+
* written by an agent-server that records none (0.3.18 and earlier, which
|
|
32
|
+
* share the default cache and may be running it): only `unrecorded` removes
|
|
33
|
+
* those, by when they were installed (`install --prune`). Returns the builds
|
|
34
|
+
* removed.
|
|
35
|
+
*/
|
|
36
|
+
export async function pruneCache(root, tools, keep, unrecorded) {
|
|
37
|
+
const now = Date.now();
|
|
38
|
+
const removed = [];
|
|
39
|
+
for (const tool of tools) {
|
|
40
|
+
const entries = await readdir(join(root, tool)).catch(() => []);
|
|
41
|
+
for (const entry of entries) {
|
|
42
|
+
if (entry.startsWith(".") || keep.has(`${tool}/${entry}`))
|
|
43
|
+
continue;
|
|
44
|
+
const marker = usedMarker(root, tool, entry);
|
|
45
|
+
const used = (await mtimeOf(marker)) ??
|
|
46
|
+
(unrecorded ? await mtimeOf(join(root, tool, entry)) : undefined);
|
|
47
|
+
if (used === undefined || now - used < PRUNE_AFTER_MS)
|
|
48
|
+
continue;
|
|
49
|
+
await rm(join(root, tool, entry), { recursive: true, force: true });
|
|
50
|
+
await rm(marker, { force: true });
|
|
51
|
+
removed.push(`${tool}/${entry}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (const entry of await readdir(join(root, ".tmp")).catch(() => [])) {
|
|
55
|
+
const path = join(root, ".tmp", entry);
|
|
56
|
+
const changed = await mtimeOf(path);
|
|
57
|
+
if (changed !== undefined && now - changed > LEFTOVER_AFTER_MS)
|
|
58
|
+
await rm(path, { recursive: true, force: true });
|
|
59
|
+
}
|
|
60
|
+
return removed;
|
|
61
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createReadStream } from "node:fs";
|
|
3
|
+
// @ref LLP 0010#p1--the-release-pins-every-build-it-can-download — trust is pinned at release, not read from the registry
|
|
4
|
+
/**
|
|
5
|
+
* What the build of `tool` at `version` for `suffix` must be. A version this
|
|
6
|
+
* release pins is checked against its table, whatever registry serves it; any
|
|
7
|
+
* other against what this machine knows of it, else only the registry.
|
|
8
|
+
*/
|
|
9
|
+
export function expectedBuild(tool, version, suffix, releases, local) {
|
|
10
|
+
const release = releases[tool];
|
|
11
|
+
const build = release.version === version ? release.builds[suffix] : undefined;
|
|
12
|
+
if (build)
|
|
13
|
+
return { source: "release", ...build };
|
|
14
|
+
const known = local?.(suffix, version);
|
|
15
|
+
return known ? { source: "local", ...known } : { source: "registry" };
|
|
16
|
+
}
|
|
17
|
+
export async function sha256Of(path) {
|
|
18
|
+
const hash = createHash("sha256");
|
|
19
|
+
for await (const chunk of createReadStream(path))
|
|
20
|
+
hash.update(chunk);
|
|
21
|
+
return hash.digest("hex");
|
|
22
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { CliProvisionError } from "../utils/errors.js";
|
|
3
|
+
/** Extracting a few hundred megabytes takes seconds; a `tar` still running after this is stuck. */
|
|
4
|
+
const EXTRACT_TIMEOUT_MS = 5 * 60_000;
|
|
5
|
+
/**
|
|
6
|
+
* Extract a .tgz into a directory using the system `tar` (BSD, GNU, and
|
|
7
|
+
* Windows 10+ libarchive all accept these flags). npm tarballs are small
|
|
8
|
+
* enough in entry count that shelling out beats maintaining a tar parser.
|
|
9
|
+
*/
|
|
10
|
+
export async function extractTarGz(tgzPath, destDir) {
|
|
11
|
+
await new Promise((resolve, reject) => {
|
|
12
|
+
const proc = spawn("tar", ["-xzf", tgzPath, "-C", destDir], {
|
|
13
|
+
env: process.env,
|
|
14
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
15
|
+
timeout: EXTRACT_TIMEOUT_MS,
|
|
16
|
+
});
|
|
17
|
+
let stderr = "";
|
|
18
|
+
proc.stderr?.on("data", (chunk) => {
|
|
19
|
+
stderr += chunk.toString();
|
|
20
|
+
});
|
|
21
|
+
proc.on("error", (error) => reject(new CliProvisionError(`Failed to run \`tar\` (${error.message}) — provisioning needs tar on PATH`, { cause: error })));
|
|
22
|
+
proc.on("exit", (code, signal) => {
|
|
23
|
+
if (code === 0)
|
|
24
|
+
resolve();
|
|
25
|
+
else
|
|
26
|
+
reject(new CliProvisionError(`tar -xzf ${tgzPath} ${signal ? `was stopped (${signal}) after ${EXTRACT_TIMEOUT_MS / 60_000} min` : `exited ${code}`}: ${stderr.trim()}`));
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { chmod, lstat, mkdir, readdir, rename, rm } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { CliProvisionError } from "../utils/errors.js";
|
|
5
|
+
import { managedDirectory, trustedBinaryIn } from "./cache-trust.js";
|
|
6
|
+
import { sha256Of } from "./checksums.js";
|
|
7
|
+
import { downloadWithIntegrity, fetchDist, withoutSecrets } from "./npm.js";
|
|
8
|
+
import { binaryIn } from "./tools.js";
|
|
9
|
+
/** At most this often an install reports its bytes. */
|
|
10
|
+
const PROGRESS_INTERVAL_MS = 250;
|
|
11
|
+
/**
|
|
12
|
+
* A tree every user may read and run, and only its owner write: folders
|
|
13
|
+
* 0755, files 0644, runnable ones 0755, never through a symlink. A staged
|
|
14
|
+
* build gets it before its rename, so what a 002 umask unpacked (Ubuntu's
|
|
15
|
+
* default) is not refused as writable by others, and a process killed after
|
|
16
|
+
* the rename leaves a finished build.
|
|
17
|
+
*/
|
|
18
|
+
export async function openToAll(path) {
|
|
19
|
+
const info = await lstat(path);
|
|
20
|
+
if (info.isSymbolicLink())
|
|
21
|
+
return;
|
|
22
|
+
if (info.isDirectory()) {
|
|
23
|
+
await chmod(path, 0o755);
|
|
24
|
+
for (const entry of await readdir(path))
|
|
25
|
+
await openToAll(join(path, entry));
|
|
26
|
+
}
|
|
27
|
+
else if (info.isFile())
|
|
28
|
+
await chmod(path, info.mode & 0o100 ? 0o755 : 0o644);
|
|
29
|
+
}
|
|
30
|
+
export function noBinary(pkg) {
|
|
31
|
+
return new CliProvisionError(`downloaded ${pkg.name}@${pkg.registryVersion} has no binary`);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Download a build, check it against what it must match, unpack it in a
|
|
35
|
+
* staging folder and rename it into `dir`. Two processes installing the same
|
|
36
|
+
* build at once both download it, and the version-keyed rename decides: the
|
|
37
|
+
* one that loses adopts the winner's tree. Answers the bytes downloaded.
|
|
38
|
+
*/
|
|
39
|
+
export async function installBuild(job) {
|
|
40
|
+
const { spec, pkg, expected, root, dir } = job;
|
|
41
|
+
const staging = join(root, ".tmp", `${pkg.name.replace("/", "-")}-${pkg.registryVersion}-${process.pid}-${randomBytes(4).toString("hex")}`);
|
|
42
|
+
try {
|
|
43
|
+
managedDirectory(root, dirname(staging), true);
|
|
44
|
+
await mkdir(staging, { mode: 0o700 });
|
|
45
|
+
const dist = await fetchDist(job.registry, pkg.name, pkg.registryVersion, job.fetch, job.timeouts);
|
|
46
|
+
if (expected.source === "release" && dist.integrity !== expected.integrity) {
|
|
47
|
+
throw new CliProvisionError(`${withoutSecrets(job.registry)} serves another ${pkg.name}@${pkg.registryVersion} than this release pins ` +
|
|
48
|
+
`(${dist.integrity.slice(0, 24)}…, pinned ${expected.integrity.slice(0, 24)}…)`,
|
|
49
|
+
// A digest's digits are no status code: classified by what it is, not its words.
|
|
50
|
+
{ category: "internal" });
|
|
51
|
+
}
|
|
52
|
+
const tgz = join(staging, "package.tgz");
|
|
53
|
+
let reportedAt = 0;
|
|
54
|
+
const bytes = await downloadWithIntegrity(dist.tarball, tgz, expected.source === "release" ? expected.integrity : dist.integrity, job.fetch, {
|
|
55
|
+
timeouts: job.timeouts,
|
|
56
|
+
onBytes: (receivedBytes, totalBytes) => {
|
|
57
|
+
const now = Date.now();
|
|
58
|
+
if (now - reportedAt < PROGRESS_INTERVAL_MS && receivedBytes !== totalBytes)
|
|
59
|
+
return;
|
|
60
|
+
reportedAt = now;
|
|
61
|
+
job.onProgress("downloading", receivedBytes, totalBytes);
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
job.onProgress("verifying", bytes, bytes);
|
|
65
|
+
const extracted = join(staging, "x");
|
|
66
|
+
await mkdir(extracted, { mode: 0o700 });
|
|
67
|
+
await job.extract(tgz, extracted);
|
|
68
|
+
const payload = await spec.payload(extracted);
|
|
69
|
+
const binary = binaryIn(payload, spec.binaries);
|
|
70
|
+
if (!binary)
|
|
71
|
+
throw noBinary(pkg);
|
|
72
|
+
const sha256 = expected.source === "registry" ? undefined : expected.sha256;
|
|
73
|
+
if (sha256) {
|
|
74
|
+
const actual = await sha256Of(binary);
|
|
75
|
+
if (actual !== sha256) {
|
|
76
|
+
throw new CliProvisionError(`${pkg.name}@${pkg.registryVersion}'s binary is not the build ${expected.source === "local" ? expected.vouchedBy : "this release pins"} names (sha256 ${actual}, expected ${sha256})`, { category: "internal" });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
await chmod(binary, 0o755);
|
|
80
|
+
await openToAll(payload);
|
|
81
|
+
managedDirectory(root, dirname(dir), true);
|
|
82
|
+
try {
|
|
83
|
+
await rename(payload, dir);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// Lost the race with another process installing the same build: the
|
|
87
|
+
// directory is version-keyed, so its tree is what we would have written.
|
|
88
|
+
if (trustedBinaryIn(root, dir, spec.binaries))
|
|
89
|
+
return bytes;
|
|
90
|
+
throw new CliProvisionError(`${dir} is there but holds no ${spec.binaries[0]}: remove it, and it installs again`, { cause: error });
|
|
91
|
+
}
|
|
92
|
+
if (!trustedBinaryIn(root, dir, spec.binaries))
|
|
93
|
+
throw noBinary(pkg);
|
|
94
|
+
return bytes;
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
await rm(staging, { recursive: true, force: true });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createReadStream } from "node:fs";
|
|
3
|
+
import { open, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { withTimeout } from "../utils/deadline.js";
|
|
5
|
+
import { CliProvisionError } from "../utils/errors.js";
|
|
6
|
+
export const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
|
|
7
|
+
/**
|
|
8
|
+
* `text` with each URL in it shown without credentials or query, where a
|
|
9
|
+
* mirror's token or a signed link would be: what an error or a log line may
|
|
10
|
+
* say, since a turn's error reaches every connection and the journal.
|
|
11
|
+
*/
|
|
12
|
+
export function withoutSecrets(text) {
|
|
13
|
+
return text.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s'"()]+/gi, (found) => {
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(found);
|
|
16
|
+
// A bare host keeps no slash it did not have.
|
|
17
|
+
const path = url.pathname === "/" && !found.endsWith("/") ? "" : url.pathname;
|
|
18
|
+
return `${url.protocol}//${url.host}${path}`;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return "<url>";
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export const DEFAULT_DOWNLOAD_TIMEOUTS = {
|
|
26
|
+
responseMs: 30_000,
|
|
27
|
+
stallMs: 30_000,
|
|
28
|
+
retryDelayMs: 1_000,
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* The metadata request is asked this many times, each waiting one deadline
|
|
32
|
+
* longer than the last (30 s, 60 s, 90 s): a slow registry answers on a later
|
|
33
|
+
* attempt instead of failing at the first deadline.
|
|
34
|
+
*/
|
|
35
|
+
const METADATA_ATTEMPTS = 3;
|
|
36
|
+
/**
|
|
37
|
+
* A download is asked again after a cut, from the bytes it has, until this
|
|
38
|
+
* many attempts in a row bring nothing new; an attempt that gets further
|
|
39
|
+
* into the file than any before it starts the count again. However much each brings, it gives up after
|
|
40
|
+
* `DOWNLOAD_ATTEMPTS_IN_ALL`.
|
|
41
|
+
*/
|
|
42
|
+
const DOWNLOAD_ATTEMPTS_IN_A_ROW = 5;
|
|
43
|
+
const DOWNLOAD_ATTEMPTS_IN_ALL = 25;
|
|
44
|
+
/** The longest wait between two attempts. */
|
|
45
|
+
const MAX_RETRY_DELAY_MS = 10_000;
|
|
46
|
+
/** A failure the next attempt may not have: no answer, a cut or a stall. Always `network`. */
|
|
47
|
+
class TransientFailure extends CliProvisionError {
|
|
48
|
+
constructor(message, options) {
|
|
49
|
+
super(message, { ...options, category: "network" });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** What a registry's answer with this status says failed. */
|
|
53
|
+
function statusCategory(status) {
|
|
54
|
+
if (status === 401 || status === 403)
|
|
55
|
+
return "auth";
|
|
56
|
+
if (status === 429)
|
|
57
|
+
return "rate_limit";
|
|
58
|
+
return status >= 500 ? "network" : "internal";
|
|
59
|
+
}
|
|
60
|
+
function messageOf(error) {
|
|
61
|
+
return error instanceof Error ? error.message : String(error);
|
|
62
|
+
}
|
|
63
|
+
function pause(ms) {
|
|
64
|
+
return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
|
|
65
|
+
}
|
|
66
|
+
/** The wait before attempt `again` + 1, after `again` attempts in a row failed. */
|
|
67
|
+
function retryDelay(timeouts, again) {
|
|
68
|
+
const base = timeouts.retryDelayMs ?? DEFAULT_DOWNLOAD_TIMEOUTS.retryDelayMs ?? 0;
|
|
69
|
+
return Math.min(MAX_RETRY_DELAY_MS, base * 2 ** Math.max(0, again - 1));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* One request: its response within `deadlineMs`, or a `TransientFailure`
|
|
73
|
+
* (no answer, a connection that failed). An answer that is not 2xx is a
|
|
74
|
+
* failure of its status's category, never asked again: a 5xx is `network`.
|
|
75
|
+
*/
|
|
76
|
+
async function request(fetchImpl, url, deadlineMs, headers) {
|
|
77
|
+
const abort = new AbortController();
|
|
78
|
+
const timer = setTimeout(() => abort.abort(), deadlineMs);
|
|
79
|
+
try {
|
|
80
|
+
const res = await fetchImpl(url, {
|
|
81
|
+
signal: abort.signal,
|
|
82
|
+
// A fresh connection each time: Bun's fetch (1.3) sends a request again by itself
|
|
83
|
+
// when a reused connection is cut mid-body, and splices the second body onto the first.
|
|
84
|
+
keepalive: false,
|
|
85
|
+
...(headers && { headers }),
|
|
86
|
+
});
|
|
87
|
+
if (!res.ok) {
|
|
88
|
+
await res.body?.cancel().catch(() => { });
|
|
89
|
+
throw new CliProvisionError(`GET ${withoutSecrets(url)} failed: ${res.status} ${res.statusText}`, { category: statusCategory(res.status) });
|
|
90
|
+
}
|
|
91
|
+
return { res, abort };
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (error instanceof CliProvisionError)
|
|
95
|
+
throw error;
|
|
96
|
+
throw new TransientFailure(abort.signal.aborted
|
|
97
|
+
? `no response within ${deadlineMs / 1000} s`
|
|
98
|
+
: withoutSecrets(messageOf(error)), { cause: error });
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** The failure an install reports after `attempts` attempts, the last of which failed with `last`. */
|
|
105
|
+
function gaveUp(url, attempts, last) {
|
|
106
|
+
return new CliProvisionError(`GET ${withoutSecrets(url)} failed${attempts > 1 ? ` after ${attempts} attempts` : ""}: ${last.message}`, { cause: last.cause ?? last, category: "network" });
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Fetch the registry metadata for one exact package version and return its
|
|
110
|
+
* tarball location + integrity. The returned tarball URL is the registry's own
|
|
111
|
+
* (works with mirrors/private registries that rewrite hosts). A request
|
|
112
|
+
* without an answer (its body included: a proxy can send the headers and
|
|
113
|
+
* stall) is asked again, each time waiting longer.
|
|
114
|
+
*/
|
|
115
|
+
export async function fetchDist(registry, packageName, version, fetchImpl = fetch, timeouts = DEFAULT_DOWNLOAD_TIMEOUTS) {
|
|
116
|
+
// Scoped names keep the literal `@` but escape the inner slash.
|
|
117
|
+
const base = registry.replace(/\/+$/, "");
|
|
118
|
+
const url = `${base}/${packageName.replace("/", "%2F")}/${version}`;
|
|
119
|
+
let body;
|
|
120
|
+
// The first answer ends the loop, whatever it holds: only no answer is asked again.
|
|
121
|
+
for (let attempt = 1;; attempt++) {
|
|
122
|
+
const deadlineMs = timeouts.responseMs * attempt;
|
|
123
|
+
try {
|
|
124
|
+
const { res, abort } = await request(fetchImpl, url, deadlineMs);
|
|
125
|
+
const read = await withTimeout(res.json(), deadlineMs);
|
|
126
|
+
if (!read) {
|
|
127
|
+
abort.abort();
|
|
128
|
+
throw new TransientFailure(`no response within ${deadlineMs / 1000} s`);
|
|
129
|
+
}
|
|
130
|
+
body = read.value;
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
// A page that is not JSON (a captive portal's, a proxy's) is a wrong answer.
|
|
135
|
+
if (error instanceof SyntaxError)
|
|
136
|
+
throw new CliProvisionError(`GET ${withoutSecrets(url)} did not answer with JSON: is something in front of the registry?`, { cause: error, category: "internal" });
|
|
137
|
+
// An answer of the wrong status is final; a body that broke off (a cut, a reset) is not.
|
|
138
|
+
if (error instanceof CliProvisionError && !(error instanceof TransientFailure))
|
|
139
|
+
throw error;
|
|
140
|
+
const failure = error instanceof TransientFailure
|
|
141
|
+
? error
|
|
142
|
+
: new TransientFailure(withoutSecrets(messageOf(error)), { cause: error });
|
|
143
|
+
if (attempt >= METADATA_ATTEMPTS)
|
|
144
|
+
throw gaveUp(url, attempt, failure);
|
|
145
|
+
await pause(retryDelay(timeouts, attempt));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
// A body that is not an object (`null`, `false`, a string) is not metadata either.
|
|
149
|
+
const dist = typeof body === "object" && body !== null
|
|
150
|
+
? body.dist
|
|
151
|
+
: undefined;
|
|
152
|
+
const { tarball, integrity } = dist ?? {};
|
|
153
|
+
if (!tarball || !integrity) {
|
|
154
|
+
throw new CliProvisionError(`Registry metadata for ${packageName}@${version} has no dist.tarball/integrity — is this version published for your platform?`, { category: "internal" });
|
|
155
|
+
}
|
|
156
|
+
return { tarball, integrity };
|
|
157
|
+
}
|
|
158
|
+
async function sizeOf(path) {
|
|
159
|
+
return (await stat(path)).size;
|
|
160
|
+
}
|
|
161
|
+
/** `bytes <start>-<end>/<total>` of a 206, its total `undefined` when `*`. */
|
|
162
|
+
function contentRange(header) {
|
|
163
|
+
const match = /^bytes (\d+)-\d+\/(\d+|\*)$/.exec(header?.trim() ?? "");
|
|
164
|
+
if (!match)
|
|
165
|
+
return undefined;
|
|
166
|
+
return { start: Number(match[1]), ...(match[2] !== "*" && { total: Number(match[2]) }) };
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* One attempt at the rest of a download: from the file's `have` bytes with a
|
|
170
|
+
* `Range` request when it has some, starting over when the server answers
|
|
171
|
+
* with the whole file instead. Appends what arrives, and fails transiently on
|
|
172
|
+
* a cut, a stall, or an end short of the stated size.
|
|
173
|
+
*/
|
|
174
|
+
async function receive(fetchImpl, url, destFile, have, deadlineMs, timeouts, onBytes) {
|
|
175
|
+
// No `If-Range`: a published npm version never changes, and the whole file's hash decides.
|
|
176
|
+
const { res, abort } = await request(fetchImpl, url, deadlineMs, have > 0 ? { range: `bytes=${have}-` } : undefined);
|
|
177
|
+
const length = Number(res.headers.get("content-length"));
|
|
178
|
+
const stated = Number.isSafeInteger(length) && length >= 0 ? length : undefined;
|
|
179
|
+
let offset = 0;
|
|
180
|
+
let total;
|
|
181
|
+
const range = res.status === 206 ? contentRange(res.headers.get("content-range")) : undefined;
|
|
182
|
+
if (res.status === 206 && range?.start === have) {
|
|
183
|
+
offset = have;
|
|
184
|
+
total = range.total ?? (stated !== undefined ? have + stated : undefined);
|
|
185
|
+
}
|
|
186
|
+
else if (res.status === 206) {
|
|
187
|
+
// A part of something else: nothing here can be kept.
|
|
188
|
+
await res.body?.cancel().catch(() => { });
|
|
189
|
+
await writeFile(destFile, "");
|
|
190
|
+
throw new TransientFailure(`asked for the bytes from ${have}, the server answered ${res.headers.get("content-range") ?? "a part it did not name"}`);
|
|
191
|
+
}
|
|
192
|
+
else
|
|
193
|
+
total = stated && stated > 0 ? stated : undefined;
|
|
194
|
+
if (!res.body)
|
|
195
|
+
throw new CliProvisionError(`GET ${withoutSecrets(url)} returned no body`);
|
|
196
|
+
// Read by hand, so a stall ends the read even where the fetch ignores its signal.
|
|
197
|
+
const reader = res.body.getReader();
|
|
198
|
+
let stalled = false;
|
|
199
|
+
let stall;
|
|
200
|
+
const armStall = () => {
|
|
201
|
+
clearTimeout(stall);
|
|
202
|
+
stall = setTimeout(() => {
|
|
203
|
+
stalled = true;
|
|
204
|
+
abort.abort();
|
|
205
|
+
void reader.cancel().catch(() => { });
|
|
206
|
+
}, timeouts.stallMs);
|
|
207
|
+
};
|
|
208
|
+
// The whole file again (the server did not honour the range): it starts over.
|
|
209
|
+
const file = await open(destFile, offset ? "a" : "w");
|
|
210
|
+
let size = offset;
|
|
211
|
+
const of = () => (total !== undefined ? `${size} of ${total}` : `${size}`);
|
|
212
|
+
try {
|
|
213
|
+
while (true) {
|
|
214
|
+
// Only the wait for the network counts as a stall, not for the disk.
|
|
215
|
+
armStall();
|
|
216
|
+
let chunk;
|
|
217
|
+
try {
|
|
218
|
+
chunk = await reader.read();
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
if (stalled)
|
|
222
|
+
break;
|
|
223
|
+
throw new TransientFailure(`the transfer was cut after ${of()} bytes (${withoutSecrets(messageOf(error))})`, {
|
|
224
|
+
cause: error,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
finally {
|
|
228
|
+
clearTimeout(stall);
|
|
229
|
+
}
|
|
230
|
+
if (stalled || chunk.done)
|
|
231
|
+
break;
|
|
232
|
+
await file.write(chunk.value);
|
|
233
|
+
size += chunk.value.byteLength;
|
|
234
|
+
// A size the response got wrong is no size.
|
|
235
|
+
onBytes?.(size, total !== undefined && size <= total ? total : undefined);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
void reader.cancel().catch(() => { });
|
|
240
|
+
throw error;
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
clearTimeout(stall);
|
|
244
|
+
await file.close();
|
|
245
|
+
}
|
|
246
|
+
if (stalled)
|
|
247
|
+
throw new TransientFailure(`stalled: nothing received for ${timeouts.stallMs / 1000} s after ${of()} bytes`);
|
|
248
|
+
if (total !== undefined && size < total)
|
|
249
|
+
throw new TransientFailure(`the transfer ended after ${of()} bytes`);
|
|
250
|
+
return { size, total };
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* The whole file into `destFile`, asked again after each transient failure
|
|
254
|
+
* from the bytes it has, and how many responses it took (`pieces`).
|
|
255
|
+
*/
|
|
256
|
+
async function fetchWhole(url, destFile, fetchImpl, timeouts, onBytes) {
|
|
257
|
+
await writeFile(destFile, "");
|
|
258
|
+
let inARow = 0;
|
|
259
|
+
// The most of the file it has had: a start over that gets as far again brings nothing new.
|
|
260
|
+
let furthest = 0;
|
|
261
|
+
for (let attempt = 1;; attempt++) {
|
|
262
|
+
const have = await sizeOf(destFile);
|
|
263
|
+
try {
|
|
264
|
+
const got = await receive(fetchImpl, url, destFile, have,
|
|
265
|
+
// A slow answer gets longer each time it fails to come.
|
|
266
|
+
timeouts.responseMs * Math.min(inARow + 1, METADATA_ATTEMPTS), timeouts, onBytes);
|
|
267
|
+
return { size: got.size, total: got.total, pieces: attempt };
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (!(error instanceof TransientFailure))
|
|
271
|
+
throw error;
|
|
272
|
+
const now = await sizeOf(destFile);
|
|
273
|
+
inARow = now > furthest ? 1 : inARow + 1;
|
|
274
|
+
furthest = Math.max(furthest, now);
|
|
275
|
+
if (inARow >= DOWNLOAD_ATTEMPTS_IN_A_ROW || attempt >= DOWNLOAD_ATTEMPTS_IN_ALL)
|
|
276
|
+
throw gaveUp(url, attempt, error);
|
|
277
|
+
await pause(retryDelay(timeouts, inARow));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
async function sha512Of(path) {
|
|
282
|
+
const hash = createHash("sha512");
|
|
283
|
+
for await (const chunk of createReadStream(path))
|
|
284
|
+
hash.update(chunk);
|
|
285
|
+
return hash.digest("base64");
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Download a tarball to `destFile`, and reject unless its sha512 matches
|
|
289
|
+
* (only sha512, what the npm registry publishes, is supported). A transfer
|
|
290
|
+
* that is cut, stalls (nothing for `stallMs`) or ends short of its stated size
|
|
291
|
+
* is asked again from the bytes it has (an HTTP `Range` request; from the
|
|
292
|
+
* start where the server does not honour one), a bounded number of times,
|
|
293
|
+
* and failing that is a `network` failure that says how far it got. The
|
|
294
|
+
* hash is checked once, over the whole file as it is on disk, so "integrity
|
|
295
|
+
* mismatch" is said only of a file that arrived whole; a file put together
|
|
296
|
+
* from more than one response whose hash is wrong is downloaded once more
|
|
297
|
+
* first, since a resumed part may not be the file's. Returns the byte count.
|
|
298
|
+
*/
|
|
299
|
+
export async function downloadWithIntegrity(url, destFile, integrity, fetchImpl = fetch, options = {}) {
|
|
300
|
+
const expected = /^sha512-([A-Za-z0-9+/=]+)$/.exec(integrity)?.[1];
|
|
301
|
+
if (!expected) {
|
|
302
|
+
throw new CliProvisionError(`Unsupported integrity format (want sha512-…): ${integrity}`);
|
|
303
|
+
}
|
|
304
|
+
const timeouts = options.timeouts ?? DEFAULT_DOWNLOAD_TIMEOUTS;
|
|
305
|
+
let got = await fetchWhole(url, destFile, fetchImpl, timeouts, options.onBytes);
|
|
306
|
+
let actual = await sha512Of(destFile);
|
|
307
|
+
const again = actual !== expected && got.pieces > 1;
|
|
308
|
+
if (again) {
|
|
309
|
+
got = await fetchWhole(url, destFile, fetchImpl, timeouts, options.onBytes);
|
|
310
|
+
actual = await sha512Of(destFile);
|
|
311
|
+
}
|
|
312
|
+
if (actual !== expected) {
|
|
313
|
+
throw new CliProvisionError(`Integrity mismatch for ${withoutSecrets(url)} (all ${got.size} bytes${got.total === undefined ? ", of a size the server did not state" : ""}${again ? ", downloaded twice" : ""}): expected sha512-${expected}, got sha512-${actual}`, { category: "internal" });
|
|
314
|
+
}
|
|
315
|
+
return got.size;
|
|
316
|
+
}
|