@instahost/cli 0.0.0-stage → 0.1.2
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 +125 -2
- package/bin/instahost.mjs +26 -0
- package/dist/api-client.js +124 -0
- package/dist/commands/context.js +1 -0
- package/dist/commands/delete.js +41 -0
- package/dist/commands/publish.js +75 -0
- package/dist/commands/share.js +83 -0
- package/dist/config.js +66 -0
- package/dist/errors.js +54 -0
- package/dist/index.js +6 -0
- package/dist/main.js +227 -0
- package/dist/output.js +79 -0
- package/dist/redact.js +24 -0
- package/dist/ttl.js +22 -0
- package/dist/upload.js +320 -0
- package/dist/vendor/paths.js +255 -0
- package/dist/walk.js +158 -0
- package/package.json +53 -3
- package/src/node-check.mjs +34 -0
- package/src/vendor/paths.ts +255 -0
package/dist/main.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// CLI entry. Never interactive.
|
|
2
|
+
// --json prints exactly one JSON document on stdout for every outcome: success, argument errors,
|
|
3
|
+
// API errors and unexpected exceptions alike.
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { ApiClient } from "./api-client.js";
|
|
6
|
+
import { VERSION, resolveApiKey, resolveApiUrl, resolveDeleteToken } from "./config.js";
|
|
7
|
+
import { CliError, EXIT, usageError } from "./errors.js";
|
|
8
|
+
import { errorDocument, printHuman, printHumanError, printJson } from "./output.js";
|
|
9
|
+
import { redact } from "./redact.js";
|
|
10
|
+
import { parseTtl } from "./ttl.js";
|
|
11
|
+
import { DEFAULT_CONCURRENCY } from "./upload.js";
|
|
12
|
+
import { deleteArtifact } from "./commands/delete.js";
|
|
13
|
+
import { publish } from "./commands/publish.js";
|
|
14
|
+
import { share } from "./commands/share.js";
|
|
15
|
+
export const HELP = `instahost ${VERSION}: instant hosting and sharing for AI agents.
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
instahost share <file> [--ttl 24h] [--access unlisted|public|private] [--name <filename>] [--content-type <type>]
|
|
19
|
+
instahost publish <dir> [--ttl 24h] [--access unlisted|public] [--include-dotfiles] [--concurrency 6]
|
|
20
|
+
instahost delete <id|url> [--token <ihd_...>] (or the owner's API key)
|
|
21
|
+
|
|
22
|
+
Options for every command:
|
|
23
|
+
--json print exactly one JSON document on stdout (success or failure)
|
|
24
|
+
--api-key <key> API key for longer lifetimes, --ttl never and higher limits (or INSTAHOST_API_KEY)
|
|
25
|
+
--verbose diagnostics on stderr (tokens and signatures are masked)
|
|
26
|
+
--help, --version
|
|
27
|
+
|
|
28
|
+
--ttl takes a number with s, m, h or d (30m, 24h, 7d), plain seconds, or "never" (needs an API key).
|
|
29
|
+
Anonymous artifacts live 24 hours by default and at most 7 days.
|
|
30
|
+
publish skips dotfiles (except .well-known), credentials (.env*, keys, .git, ...) and OS metadata,
|
|
31
|
+
and lists them under "skipped". Sites must use relative URLs (Vite: base: "./").
|
|
32
|
+
delete uses --token, else --api-key, else INSTAHOST_DELETE_TOKEN, else INSTAHOST_API_KEY; the
|
|
33
|
+
environment keeps the token out of the process list.
|
|
34
|
+
|
|
35
|
+
Exit codes: 0 ok, 1 internal error, 2 usage, 3 local input (missing file, no index.html, invalid or
|
|
36
|
+
sensitive name), 4 authentication or authorization (401, 403), 5 rejected by the server (400, 413,
|
|
37
|
+
415, 422 and other 4xx), 6 rate limited or over quota (429), 7 network or server failure, 8
|
|
38
|
+
publication failed (upload mismatch, incomplete upload, upload window closed), 9 not found (404).
|
|
39
|
+
|
|
40
|
+
Run it with npx (Node.js 20 or later), or install it once with npm i -g @instahost/cli:
|
|
41
|
+
npx -y @instahost/cli share ./screenshot.png --json
|
|
42
|
+
The npm package named "instahost" (without the @instahost/ scope) is unrelated to this project;
|
|
43
|
+
do not install it.
|
|
44
|
+
`;
|
|
45
|
+
/** Every option the CLI accepts; the docs tests check that each documented flag is one of these. */
|
|
46
|
+
export const OPTIONS = {
|
|
47
|
+
json: { type: "boolean" },
|
|
48
|
+
"api-url": { type: "string" },
|
|
49
|
+
"api-key": { type: "string" },
|
|
50
|
+
verbose: { type: "boolean" },
|
|
51
|
+
help: { type: "boolean", short: "h" },
|
|
52
|
+
version: { type: "boolean" },
|
|
53
|
+
ttl: { type: "string" },
|
|
54
|
+
access: { type: "string" },
|
|
55
|
+
name: { type: "string" },
|
|
56
|
+
"content-type": { type: "string" },
|
|
57
|
+
"include-dotfiles": { type: "boolean" },
|
|
58
|
+
concurrency: { type: "string" },
|
|
59
|
+
token: { type: "string" },
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Options the CLI accepts but never documents (help, READMEs, skill, website). InstaHost cannot be
|
|
63
|
+
* self-hosted: --api-url and INSTAHOST_API_URL exist only for the InstaHost team, to point the CLI
|
|
64
|
+
* at a local or test deployment. The docs tests check that no public text mentions them.
|
|
65
|
+
*/
|
|
66
|
+
export const UNDOCUMENTED_OPTIONS = ["api-url"];
|
|
67
|
+
/** Options every command accepts. */
|
|
68
|
+
export const GLOBAL = ["json", "api-url", "api-key", "verbose", "help", "version"];
|
|
69
|
+
/** Options per command, on top of GLOBAL. */
|
|
70
|
+
export const PER_COMMAND = {
|
|
71
|
+
share: ["ttl", "access", "name", "content-type"],
|
|
72
|
+
publish: ["ttl", "access", "include-dotfiles", "concurrency"],
|
|
73
|
+
delete: ["token"],
|
|
74
|
+
};
|
|
75
|
+
function defaultStreams() {
|
|
76
|
+
return {
|
|
77
|
+
stdout: (text) => void process.stdout.write(text),
|
|
78
|
+
stderr: (text) => void process.stderr.write(text),
|
|
79
|
+
stderrIsTty: Boolean(process.stderr.isTTY),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function parse(argv) {
|
|
83
|
+
let parsed;
|
|
84
|
+
try {
|
|
85
|
+
parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
throw usageError(`${err instanceof Error ? err.message : String(err)} (see instahost --help).`);
|
|
89
|
+
}
|
|
90
|
+
const [command, ...positionals] = parsed.positionals;
|
|
91
|
+
return { command, positionals, values: parsed.values };
|
|
92
|
+
}
|
|
93
|
+
function choice(flag, value, allowed, fallback) {
|
|
94
|
+
if (value === undefined)
|
|
95
|
+
return fallback;
|
|
96
|
+
if (allowed.includes(value))
|
|
97
|
+
return value;
|
|
98
|
+
throw usageError(`--${flag} must be one of ${allowed.join(", ")}.`);
|
|
99
|
+
}
|
|
100
|
+
async function run(argv, deps, streams, json) {
|
|
101
|
+
const { command, positionals, values } = parse(argv);
|
|
102
|
+
if (values.version)
|
|
103
|
+
return "version";
|
|
104
|
+
if (values.help || command === undefined || command === "help")
|
|
105
|
+
return "help";
|
|
106
|
+
const allowed = Object.hasOwn(PER_COMMAND, command) ? PER_COMMAND[command] : undefined;
|
|
107
|
+
if (!allowed)
|
|
108
|
+
throw usageError(`Unknown command ${JSON.stringify(command)}; use share, publish or delete.`);
|
|
109
|
+
for (const key of Object.keys(values)) {
|
|
110
|
+
if (!GLOBAL.includes(key) && !allowed.includes(key))
|
|
111
|
+
throw usageError(`--${key} does not apply to ${command}.`);
|
|
112
|
+
}
|
|
113
|
+
if (positionals.length !== 1)
|
|
114
|
+
throw usageError(`${command} takes exactly one ${command === "share" ? "file" : command === "publish" ? "directory" : "artifact id"}.`);
|
|
115
|
+
const target = positionals[0];
|
|
116
|
+
const apiUrl = resolveApiUrl(values["api-url"], deps.env);
|
|
117
|
+
const apiKey = resolveApiKey(values["api-key"], deps.env);
|
|
118
|
+
const client = new ApiClient({ apiUrl, log: values.verbose ? (line) => streams.stderr(`${line}\n`) : undefined, sleep: deps.sleep, fetch: deps.fetch });
|
|
119
|
+
const showProgress = !json && !values.verbose && streams.stderrIsTty;
|
|
120
|
+
const ctx = {
|
|
121
|
+
client,
|
|
122
|
+
apiKey,
|
|
123
|
+
fetch: deps.fetch,
|
|
124
|
+
onProgress: showProgress
|
|
125
|
+
? (done, total) => {
|
|
126
|
+
streams.stderr(`\ruploading ${done}/${total}${done === total ? "\n" : ""}`);
|
|
127
|
+
progress.open = done !== total;
|
|
128
|
+
}
|
|
129
|
+
: undefined,
|
|
130
|
+
};
|
|
131
|
+
const lifetime = values.ttl === undefined ? null : parseTtl(values.ttl);
|
|
132
|
+
if (command === "share") {
|
|
133
|
+
return share(ctx, {
|
|
134
|
+
file: target,
|
|
135
|
+
lifetime,
|
|
136
|
+
access: choice("access", values.access, ["unlisted", "public", "private"], "unlisted"),
|
|
137
|
+
name: values.name,
|
|
138
|
+
contentType: values["content-type"],
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
if (command === "publish") {
|
|
142
|
+
if (values.access === "private")
|
|
143
|
+
throw usageError("Private sites are not supported; publish with --access unlisted or public, or share single files privately.");
|
|
144
|
+
const concurrency = values.concurrency === undefined ? DEFAULT_CONCURRENCY : Number(values.concurrency);
|
|
145
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
|
|
146
|
+
throw usageError("--concurrency must be an integer from 1 to 16.");
|
|
147
|
+
return publish(ctx, {
|
|
148
|
+
dir: target,
|
|
149
|
+
lifetime,
|
|
150
|
+
access: choice("access", values.access, ["unlisted", "public"], "unlisted"),
|
|
151
|
+
includeDotfiles: values["include-dotfiles"] ?? false,
|
|
152
|
+
concurrency,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (command === "delete") {
|
|
156
|
+
// Flags before the environment: --token, then --api-key, then
|
|
157
|
+
// INSTAHOST_DELETE_TOKEN, then INSTAHOST_API_KEY.
|
|
158
|
+
const credential = resolveDeleteToken(values.token, {}) ?? (values["api-key"] !== undefined ? apiKey : null) ?? resolveDeleteToken(undefined, deps.env) ?? apiKey;
|
|
159
|
+
return deleteArtifact(ctx, { ref: target, credential });
|
|
160
|
+
}
|
|
161
|
+
throw usageError(`Unknown command ${JSON.stringify(command)}; use share, publish or delete.`);
|
|
162
|
+
}
|
|
163
|
+
/** Whether a "\ruploading n/N" progress line is still open on stderr (it must end before any error). */
|
|
164
|
+
const progress = { open: false };
|
|
165
|
+
/**
|
|
166
|
+
* Last resort for a real process: an error that escapes main() still ends as one JSON document
|
|
167
|
+
* (or one stderr line) and exit code 1, never a Node stack trace on stdout.
|
|
168
|
+
*/
|
|
169
|
+
function installCrashHandlers(argv, streams) {
|
|
170
|
+
const crash = (err) => {
|
|
171
|
+
const doc = errorDocument(new CliError("internal_error", `Unexpected error: ${err instanceof Error ? err.name : "unknown"}`, EXIT.internal));
|
|
172
|
+
if (argv.includes("--json"))
|
|
173
|
+
printJson(streams, doc);
|
|
174
|
+
else
|
|
175
|
+
streams.stderr(`instahost: ${doc.error.message}\n`);
|
|
176
|
+
process.exit(EXIT.internal);
|
|
177
|
+
};
|
|
178
|
+
process.once("uncaughtException", crash);
|
|
179
|
+
process.once("unhandledRejection", crash);
|
|
180
|
+
}
|
|
181
|
+
/** Runs the CLI; returns the exit code. Never throws. */
|
|
182
|
+
export async function main(argv, deps = {}) {
|
|
183
|
+
const streams = deps.streams ?? defaultStreams();
|
|
184
|
+
if (!deps.streams)
|
|
185
|
+
installCrashHandlers(argv, streams);
|
|
186
|
+
const json = argv.includes("--json");
|
|
187
|
+
const env = deps.env ?? process.env;
|
|
188
|
+
const fail = (err) => {
|
|
189
|
+
if (progress.open) {
|
|
190
|
+
streams.stderr("\n");
|
|
191
|
+
progress.open = false;
|
|
192
|
+
}
|
|
193
|
+
const cliError = err instanceof CliError ? err : new CliError("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
|
|
194
|
+
if (json)
|
|
195
|
+
printJson(streams, errorDocument(cliError));
|
|
196
|
+
else
|
|
197
|
+
printHumanError(streams, cliError);
|
|
198
|
+
if (argv.includes("--verbose") && !(err instanceof CliError) && err instanceof Error && err.stack)
|
|
199
|
+
streams.stderr(`${redact(err.stack)}\n`);
|
|
200
|
+
return cliError.exitCode;
|
|
201
|
+
};
|
|
202
|
+
try {
|
|
203
|
+
const result = await run(argv, { ...deps, env }, streams, json);
|
|
204
|
+
if (result === "help") {
|
|
205
|
+
if (json)
|
|
206
|
+
printJson(streams, { ok: true, help: HELP });
|
|
207
|
+
else
|
|
208
|
+
streams.stdout(HELP);
|
|
209
|
+
return EXIT.ok;
|
|
210
|
+
}
|
|
211
|
+
if (result === "version") {
|
|
212
|
+
if (json)
|
|
213
|
+
printJson(streams, { ok: true, version: VERSION });
|
|
214
|
+
else
|
|
215
|
+
streams.stdout(`${VERSION}\n`);
|
|
216
|
+
return EXIT.ok;
|
|
217
|
+
}
|
|
218
|
+
if (json)
|
|
219
|
+
printJson(streams, result);
|
|
220
|
+
else
|
|
221
|
+
printHuman(streams, result);
|
|
222
|
+
return EXIT.ok;
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
return fail(err);
|
|
226
|
+
}
|
|
227
|
+
}
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { redact } from "./redact.js";
|
|
2
|
+
/** Redacts every string inside a JSON-like value (never the serialised text, which it could corrupt). */
|
|
3
|
+
export function redactValue(value) {
|
|
4
|
+
if (typeof value === "string")
|
|
5
|
+
return redact(value);
|
|
6
|
+
if (Array.isArray(value))
|
|
7
|
+
return value.map(redactValue);
|
|
8
|
+
if (value && typeof value === "object")
|
|
9
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redactValue(v)]));
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The --json failure document. Details are redacted; an artifact created before the failure is
|
|
14
|
+
* added afterwards, unredacted, because its delete token is the only way to remove it.
|
|
15
|
+
*/
|
|
16
|
+
export function errorDocument(err) {
|
|
17
|
+
let details = err.details && Object.keys(err.details).length ? redactValue(err.details) : undefined;
|
|
18
|
+
if (err.artifact)
|
|
19
|
+
details = { ...details, artifact: { ...err.artifact } };
|
|
20
|
+
return { ok: false, error: { code: err.code, message: redact(err.message), ...(details ? { details } : {}), exit_code: err.exitCode } };
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The delete command printed in human output. It names the scoped package on purpose: most users run
|
|
24
|
+
* the CLI through npx and have no `instahost` on PATH, and the obvious fix, `npx instahost`, would run
|
|
25
|
+
* the unrelated unscoped npm package and hand it the delete token.
|
|
26
|
+
*/
|
|
27
|
+
export const DELETE_COMMAND = "npx -y @instahost/cli delete";
|
|
28
|
+
const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
|
|
29
|
+
/** Text for a terminal: control, line-separator and bidi characters become visible escapes. */
|
|
30
|
+
export function terminalSafe(text) {
|
|
31
|
+
return text.replace(CONTROL, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
32
|
+
}
|
|
33
|
+
export function printJson(streams, doc) {
|
|
34
|
+
streams.stdout(`${JSON.stringify(doc)}\n`);
|
|
35
|
+
}
|
|
36
|
+
const SKIP_LABEL = {
|
|
37
|
+
sensitive: "looks like a credential or VCS data",
|
|
38
|
+
os_metadata: "operating-system metadata",
|
|
39
|
+
dotfile: "dotfile (use --include-dotfiles)",
|
|
40
|
+
symlink: "symbolic link (never followed)",
|
|
41
|
+
special: "not a regular file",
|
|
42
|
+
};
|
|
43
|
+
// Human output escapes control characters: file names and server strings are untrusted and could
|
|
44
|
+
// otherwise carry terminal escape sequences (clipboard writes, hidden or rewritten lines).
|
|
45
|
+
export function printHuman(streams, doc) {
|
|
46
|
+
const t = terminalSafe;
|
|
47
|
+
if ("delete_token" in doc) {
|
|
48
|
+
for (const s of doc.skipped)
|
|
49
|
+
streams.stderr(`skipped ${t(s.path)} (${SKIP_LABEL[s.reason]})\n`);
|
|
50
|
+
for (const w of doc.warnings)
|
|
51
|
+
streams.stderr(`warning ${t(w.message)}${w.paths?.length ? `: ${t(w.paths.join(", "))}` : ""}\n`);
|
|
52
|
+
const lines = [`URL ${t(doc.url)}`];
|
|
53
|
+
if (doc.access_url)
|
|
54
|
+
lines.push(`Access ${t(doc.access_url)}`);
|
|
55
|
+
lines.push(`Expires ${doc.expires_at ?? "never"}`, `Delete ${DELETE_COMMAND} ${doc.id} --token ${t(doc.delete_token)}`);
|
|
56
|
+
streams.stdout(`${lines.join("\n")}\n`);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
streams.stdout(`${doc.status === "blocked" ? "Blocked (taken down by the operator)" : "Deleted"} ${t(doc.id)}\n`);
|
|
60
|
+
}
|
|
61
|
+
export function printHumanError(streams, err) {
|
|
62
|
+
const t = (text) => terminalSafe(redact(text));
|
|
63
|
+
const lines = [`instahost: ${t(err.message)}`];
|
|
64
|
+
const details = err.details ?? {};
|
|
65
|
+
const paths = Array.isArray(details.paths) ? details.paths : [];
|
|
66
|
+
for (const p of paths.slice(0, 20)) {
|
|
67
|
+
if (typeof p === "string")
|
|
68
|
+
lines.push(` ${t(p)}`);
|
|
69
|
+
else if (p && typeof p === "object" && "path" in p)
|
|
70
|
+
lines.push(` ${t(String(p.path))}${"reason" in p ? ` (${t(String(p.reason))})` : ""}`);
|
|
71
|
+
}
|
|
72
|
+
if (typeof details.reason === "string" && !paths.length && !err.message.includes(details.reason))
|
|
73
|
+
lines[0] += ` (${t(details.reason)})`;
|
|
74
|
+
if (err.artifact) {
|
|
75
|
+
const a = err.artifact;
|
|
76
|
+
lines.push(`instahost: the artifact may exist (${t(a.url)}); delete it with: ${DELETE_COMMAND} ${a.id} --token ${terminalSafe(a.delete_token)}`);
|
|
77
|
+
}
|
|
78
|
+
streams.stderr(`${lines.join("\n")}\n`);
|
|
79
|
+
}
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Masks credentials and signatures in diagnostics. Applied to every line
|
|
2
|
+
// written to stderr and to error messages; the result document itself carries the tokens the user
|
|
3
|
+
// asked for (delete token, access token and URL) and is not masked.
|
|
4
|
+
const TOKEN = /\bih([dak])_[A-Za-z0-9_-]+/g;
|
|
5
|
+
const SIGNED_PARAM = /\b(X-Amz-(?:Signature|Credential|Security-Token))=[^&\s"']+/gi;
|
|
6
|
+
const TOKEN_PARAM = /([?&]token=)[^&\s"']+/gi;
|
|
7
|
+
const BEARER = /\b(Bearer\s+)[^\s"']+/gi;
|
|
8
|
+
export function redact(text) {
|
|
9
|
+
return text
|
|
10
|
+
.replace(TOKEN, (_m, kind) => `ih${kind}_***`)
|
|
11
|
+
.replace(SIGNED_PARAM, "$1=***")
|
|
12
|
+
.replace(TOKEN_PARAM, "$1***")
|
|
13
|
+
.replace(BEARER, "$1***");
|
|
14
|
+
}
|
|
15
|
+
/** A URL safe for diagnostics: origin and path only (no query string, which may hold a signature). */
|
|
16
|
+
export function describeUrl(url) {
|
|
17
|
+
try {
|
|
18
|
+
const u = new URL(url);
|
|
19
|
+
return redact(`${u.origin}${u.pathname}`);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return "<invalid url>";
|
|
23
|
+
}
|
|
24
|
+
}
|
package/dist/ttl.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// --ttl parsing: <n>s|m|h|d, a bare number of seconds, or "never"
|
|
2
|
+
// (persistent: true, which needs an API key). The server enforces the minimum and maximum.
|
|
3
|
+
import { usageError } from "./errors.js";
|
|
4
|
+
const UNITS = { s: 1, m: 60, h: 3600, d: 86_400 };
|
|
5
|
+
export function parseTtl(raw) {
|
|
6
|
+
const value = raw.trim().toLowerCase();
|
|
7
|
+
if (value === "never")
|
|
8
|
+
return { kind: "persistent" };
|
|
9
|
+
const m = /^(\d{1,12})([smhd]?)$/.exec(value);
|
|
10
|
+
if (!m)
|
|
11
|
+
throw usageError(`Invalid --ttl ${JSON.stringify(raw)}: use a number with s, m, h or d (for example 30m, 24h, 7d), or never.`);
|
|
12
|
+
const seconds = Number(m[1]) * UNITS[m[2] || "s"];
|
|
13
|
+
if (!Number.isSafeInteger(seconds) || seconds < 1)
|
|
14
|
+
throw usageError(`Invalid --ttl ${JSON.stringify(raw)}: it must be at least 1 second.`);
|
|
15
|
+
return { kind: "ttl", seconds };
|
|
16
|
+
}
|
|
17
|
+
/** The create request fields for a lifetime (none when the server default applies). */
|
|
18
|
+
export function lifetimeFields(lifetime) {
|
|
19
|
+
if (lifetime === null)
|
|
20
|
+
return {};
|
|
21
|
+
return lifetime.kind === "persistent" ? { persistent: true } : { ttl_seconds: lifetime.seconds };
|
|
22
|
+
}
|
package/dist/upload.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// Uploads and publication.
|
|
2
|
+
// - One presigned PUT per file, body streamed from disk (fs.openAsBlob), signed headers replayed
|
|
3
|
+
// exactly. A returned content-length header is checked against the file, not sent explicitly.
|
|
4
|
+
// - Batches of upload URLs are requested through /uploads just before use; `concurrency` PUTs run
|
|
5
|
+
// at a time (default 6, 1 to 16).
|
|
6
|
+
// - Per file: up to 3 retries on network errors, 429 and 5xx (1 s, 2 s, 4 s). 412 means the object
|
|
7
|
+
// already exists (an earlier attempt landed). A URL about to expire is replaced before use, and a
|
|
8
|
+
// 403 (usually an expired URL) re-issues once per file, then retries; either way the URLs of all
|
|
9
|
+
// the batch's unfinished files that are about to expire are re-issued together in one /uploads
|
|
10
|
+
// call. 400 BadDigest means the file changed after hashing (exit 3). Other 4xx are fatal.
|
|
11
|
+
// - The bytes come from the file that was hashed (same device and inode, not a symlink).
|
|
12
|
+
// - Presigned URLs must be https, or plain http on loopback while the API is plain-http loopback
|
|
13
|
+
// (the local R2 emulator); they never get an Authorization header.
|
|
14
|
+
// - /complete answering 409 upload_incomplete re-uploads details.missing, then completes again, at
|
|
15
|
+
// most 3 complete calls in all (the server allows MAX_COMPLETE_ATTEMPTS = 4).
|
|
16
|
+
import { openAsBlob } from "node:fs";
|
|
17
|
+
import { lstat } from "node:fs/promises";
|
|
18
|
+
import { BACKOFF_SECONDS, RETRIES } from "./api-client.js";
|
|
19
|
+
import { isLoopbackHost } from "./config.js";
|
|
20
|
+
import { CliError, EXIT, inputError } from "./errors.js";
|
|
21
|
+
import { describeUrl } from "./redact.js";
|
|
22
|
+
export const MAX_COMPLETE_CALLS = 3;
|
|
23
|
+
export const DEFAULT_CONCURRENCY = 6;
|
|
24
|
+
/** Re-issue requests arriving within this window share one /uploads call. */
|
|
25
|
+
const REFRESH_GATHER_MS = 25;
|
|
26
|
+
/** URLs with less life left than this are re-issued before use rather than tried. */
|
|
27
|
+
const MIN_URL_LIFE_MS = 5_000;
|
|
28
|
+
/** The S3 error code in an XML error body, for diagnostics. */
|
|
29
|
+
function s3Code(body) {
|
|
30
|
+
return /<Code>([^<]{1,64})<\/Code>/.exec(body)?.[1] ?? null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Presigned URLs must be https. Plain http is accepted only for the local R2 emulator: a loopback
|
|
34
|
+
* host, and only while the API itself is plain-http loopback (a local development server).
|
|
35
|
+
*/
|
|
36
|
+
export function checkUploadUrl(raw, apiUrl) {
|
|
37
|
+
let url;
|
|
38
|
+
try {
|
|
39
|
+
url = new URL(raw);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new CliError("unsafe_url", "The API returned an invalid upload URL.", EXIT.network);
|
|
43
|
+
}
|
|
44
|
+
const api = new URL(apiUrl);
|
|
45
|
+
const localHttp = url.protocol === "http:" && isLoopbackHost(url.hostname) && api.protocol === "http:" && isLoopbackHost(api.hostname);
|
|
46
|
+
if (url.protocol !== "https:" && !localHttp) {
|
|
47
|
+
throw new CliError("unsafe_url", "The API returned an upload URL that is not https.", EXIT.network, { url: describeUrl(raw) });
|
|
48
|
+
}
|
|
49
|
+
return url;
|
|
50
|
+
}
|
|
51
|
+
/** The fields this module reads from an instruction batch; anything else is a broken server. */
|
|
52
|
+
export function checkBatch(batch, where) {
|
|
53
|
+
const b = batch;
|
|
54
|
+
const ok = !!b &&
|
|
55
|
+
typeof b.expires_at === "string" &&
|
|
56
|
+
Array.isArray(b.files) &&
|
|
57
|
+
b.files.every((f) => f && typeof f.path === "string" && typeof f.url === "string" && f.method === "PUT" && f.headers !== null && typeof f.headers === "object");
|
|
58
|
+
if (!ok)
|
|
59
|
+
throw new CliError("bad_response", `The API's answer to ${where} has no valid upload instructions.`, EXIT.network);
|
|
60
|
+
}
|
|
61
|
+
/** The fields read from a create answer (batch_size must be at least 1, or batching never ends). */
|
|
62
|
+
export function checkCreated(created) {
|
|
63
|
+
const c = created;
|
|
64
|
+
checkBatch(c?.upload, "create");
|
|
65
|
+
const u = c?.upload;
|
|
66
|
+
const ok = typeof c?.artifact?.id === "string" &&
|
|
67
|
+
typeof c.delete_token === "string" &&
|
|
68
|
+
Number.isInteger(u.batch_size) &&
|
|
69
|
+
u.batch_size >= 1 &&
|
|
70
|
+
typeof u.uploads_url === "string" &&
|
|
71
|
+
typeof u.complete_url === "string";
|
|
72
|
+
if (!ok)
|
|
73
|
+
throw new CliError("bad_response", "The API's answer to create is incomplete.", EXIT.network);
|
|
74
|
+
}
|
|
75
|
+
/** The fields read from a published artifact. */
|
|
76
|
+
export function checkArtifact(artifact, where) {
|
|
77
|
+
const a = artifact;
|
|
78
|
+
if (!a || typeof a.id !== "string" || typeof a.url !== "string")
|
|
79
|
+
throw new CliError("bad_response", `The API's answer to ${where} has no artifact.`, EXIT.network);
|
|
80
|
+
}
|
|
81
|
+
class Uploader {
|
|
82
|
+
#s;
|
|
83
|
+
#fetch;
|
|
84
|
+
#minLifeMs;
|
|
85
|
+
#cache = new Map();
|
|
86
|
+
#done = new Set();
|
|
87
|
+
#generation = 0;
|
|
88
|
+
/** Paths waiting for the next re-issue round, and that round. */
|
|
89
|
+
#pending = new Set();
|
|
90
|
+
#round = null;
|
|
91
|
+
#progress = 0;
|
|
92
|
+
constructor(session) {
|
|
93
|
+
this.#s = session;
|
|
94
|
+
this.#fetch = session.fetch ?? fetch;
|
|
95
|
+
this.#minLifeMs = session.minUrlLifeMs ?? MIN_URL_LIFE_MS;
|
|
96
|
+
this.remember(session.created.upload);
|
|
97
|
+
}
|
|
98
|
+
remember(batch) {
|
|
99
|
+
const expiresAt = Date.parse(batch.expires_at);
|
|
100
|
+
const generation = ++this.#generation;
|
|
101
|
+
const issuedAt = Date.now();
|
|
102
|
+
for (const instruction of batch.files) {
|
|
103
|
+
this.#cache.set(instruction.path, { instruction, expiresAt: Number.isNaN(expiresAt) ? 0 : expiresAt, issuedAt, generation });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
get #token() {
|
|
107
|
+
return manageToken(this.#s);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* True when a file has no URL, or its URL aged to under the minimum life. A URL that was already
|
|
111
|
+
* that short when issued (the server caps URLs at the end of the upload window) is used as it is:
|
|
112
|
+
* a new one would be no longer.
|
|
113
|
+
*/
|
|
114
|
+
#stale(path, now = Date.now()) {
|
|
115
|
+
const c = this.#cache.get(path);
|
|
116
|
+
return !c || (c.expiresAt - now < this.#minLifeMs && c.expiresAt - c.issuedAt >= this.#minLifeMs);
|
|
117
|
+
}
|
|
118
|
+
async issue(paths) {
|
|
119
|
+
const size = this.#s.created.upload.batch_size;
|
|
120
|
+
for (let i = 0; i < paths.length; i += size) {
|
|
121
|
+
const r = await this.#s.client.call("POST", this.#s.created.upload.uploads_url, {
|
|
122
|
+
body: { paths: paths.slice(i, i + size) },
|
|
123
|
+
token: this.#token,
|
|
124
|
+
idempotent: true,
|
|
125
|
+
phase: "publish",
|
|
126
|
+
});
|
|
127
|
+
checkBatch(r?.upload, "/uploads");
|
|
128
|
+
this.remember(r.upload);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Gets a new URL for `path` (each file may re-issue once on 403). Requests that
|
|
133
|
+
* arrive within REFRESH_GATHER_MS share one /uploads call, together with every other unfinished
|
|
134
|
+
* file of the batch whose URL is about to expire; a caller whose URL is still the one it saw
|
|
135
|
+
* (generation) after a round joins the next, so later waves of expiry are covered too. The
|
|
136
|
+
* server caps issuance at MAX_URL_ISSUES_PER_FILE, which bounds this.
|
|
137
|
+
*/
|
|
138
|
+
async #refresh(batch, path, seenGeneration) {
|
|
139
|
+
while ((this.#cache.get(path)?.generation ?? 0) <= seenGeneration) {
|
|
140
|
+
this.#pending.add(path);
|
|
141
|
+
this.#round ??= this.#runRound(batch);
|
|
142
|
+
await this.#round;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async #runRound(batch) {
|
|
146
|
+
try {
|
|
147
|
+
await new Promise((resolve) => setTimeout(resolve, REFRESH_GATHER_MS));
|
|
148
|
+
const now = Date.now();
|
|
149
|
+
const paths = batch.filter((f) => !this.#done.has(f.path) && (this.#pending.has(f.path) || this.#stale(f.path, now))).map((f) => f.path);
|
|
150
|
+
this.#pending.clear();
|
|
151
|
+
if (paths.length)
|
|
152
|
+
await this.issue(paths);
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
this.#round = null;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async uploadAll(files) {
|
|
159
|
+
const size = this.#s.created.upload.batch_size;
|
|
160
|
+
for (let i = 0; i < files.length; i += size) {
|
|
161
|
+
const batch = files.slice(i, i + size);
|
|
162
|
+
const now = Date.now();
|
|
163
|
+
const stale = batch.filter((f) => this.#stale(f.path, now)).map((f) => f.path);
|
|
164
|
+
if (stale.length)
|
|
165
|
+
await this.issue(stale);
|
|
166
|
+
await this.#pool(batch);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async #pool(batch) {
|
|
170
|
+
let next = 0;
|
|
171
|
+
let stopped = false;
|
|
172
|
+
const worker = async () => {
|
|
173
|
+
while (next < batch.length && !stopped) {
|
|
174
|
+
const file = batch[next++];
|
|
175
|
+
try {
|
|
176
|
+
await this.#uploadOne(file, batch);
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
stopped = true; // the other workers finish their current file and stop
|
|
180
|
+
throw err;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const workers = Array.from({ length: Math.min(this.#s.concurrency, batch.length) }, worker);
|
|
185
|
+
const results = await Promise.allSettled(workers);
|
|
186
|
+
const failed = results.find((r) => r.status === "rejected");
|
|
187
|
+
if (failed)
|
|
188
|
+
throw failed.reason;
|
|
189
|
+
}
|
|
190
|
+
/** The file's bytes, from the same file that was hashed: never through a symlink swapped in since. */
|
|
191
|
+
async #body(file) {
|
|
192
|
+
const changed = () => inputError("file_changed", `${file.path} changed since it was hashed; try again.`, { path: file.path });
|
|
193
|
+
let info;
|
|
194
|
+
try {
|
|
195
|
+
info = await lstat(file.absPath);
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
throw inputError("unreadable_file", `${file.path} can no longer be read.`, { path: file.path });
|
|
199
|
+
}
|
|
200
|
+
if (!info.isFile() || info.size !== file.size || (file.ino !== undefined && (info.ino !== file.ino || info.dev !== file.dev)))
|
|
201
|
+
throw changed();
|
|
202
|
+
const body = await openAsBlob(file.absPath).catch(() => {
|
|
203
|
+
throw inputError("unreadable_file", `${file.path} can no longer be read.`, { path: file.path });
|
|
204
|
+
});
|
|
205
|
+
if (body.size !== file.size)
|
|
206
|
+
throw changed();
|
|
207
|
+
return body;
|
|
208
|
+
}
|
|
209
|
+
async #uploadOne(file, batch) {
|
|
210
|
+
let reissued = false;
|
|
211
|
+
let refreshedBeforeUse = false;
|
|
212
|
+
let retries = 0;
|
|
213
|
+
for (;;) {
|
|
214
|
+
const cached = this.#cache.get(file.path);
|
|
215
|
+
if (!cached)
|
|
216
|
+
throw new CliError("bad_response", `The API returned no upload URL for ${file.path}.`, EXIT.network, { path: file.path });
|
|
217
|
+
// A URL about to expire is replaced before use (once: near the end of the upload window the
|
|
218
|
+
// server only issues short-lived URLs, which are then used as they are).
|
|
219
|
+
if (!refreshedBeforeUse && this.#stale(file.path)) {
|
|
220
|
+
refreshedBeforeUse = true;
|
|
221
|
+
await this.#refresh(batch, file.path, cached.generation);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const { instruction } = cached;
|
|
225
|
+
const url = checkUploadUrl(instruction.url, this.#s.client.apiUrl);
|
|
226
|
+
const headers = {};
|
|
227
|
+
for (const [name, value] of Object.entries(instruction.headers)) {
|
|
228
|
+
if (name.toLowerCase() === "content-length") {
|
|
229
|
+
if (Number(value) !== file.size)
|
|
230
|
+
throw inputError("file_changed", `${file.path} changed size since it was hashed; try again.`, { path: file.path });
|
|
231
|
+
continue; // fetch sends the length of the body itself
|
|
232
|
+
}
|
|
233
|
+
headers[name] = value;
|
|
234
|
+
}
|
|
235
|
+
const body = await this.#body(file);
|
|
236
|
+
let status;
|
|
237
|
+
let detail = null;
|
|
238
|
+
try {
|
|
239
|
+
const res = await this.#fetch(url, { method: instruction.method, headers, body, redirect: "error" });
|
|
240
|
+
status = res.status;
|
|
241
|
+
detail = status >= 400 ? s3Code(await res.text()) : (await res.arrayBuffer(), null);
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
status = 0;
|
|
245
|
+
detail = err instanceof Error ? (err.cause?.code ?? err.name) : "unknown";
|
|
246
|
+
}
|
|
247
|
+
this.#s.client.log(`put ${file.path} -> ${status || "network error"}${detail ? ` (${detail})` : ""}`);
|
|
248
|
+
if (status === 200 || status === 412) {
|
|
249
|
+
this.#done.add(file.path);
|
|
250
|
+
this.#s.onProgress?.(++this.#progress, this.#s.files.length);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (status === 403 && !reissued) {
|
|
254
|
+
reissued = true;
|
|
255
|
+
await this.#refresh(batch, file.path, cached.generation);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
if ((status === 0 || status === 429 || status >= 500) && retries < RETRIES) {
|
|
259
|
+
await this.#s.client.sleep(BACKOFF_SECONDS[retries++] ?? 4);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
// The signed Content-MD5 no longer matches: the file changed (at the same size) after hashing.
|
|
263
|
+
if (status === 400 && (detail === "BadDigest" || detail === "InvalidDigest")) {
|
|
264
|
+
throw inputError("file_changed", `${file.path} changed since it was hashed (storage refused its checksum); try again.`, { path: file.path });
|
|
265
|
+
}
|
|
266
|
+
const reason = status === 0 ? `network error (${detail})` : `HTTP ${status}${detail ? ` ${detail}` : ""}`;
|
|
267
|
+
throw new CliError("upload_failed", `Uploading ${file.path} failed: ${reason}.`, EXIT.network, { path: file.path, status: status || null, s3_code: status ? detail : null });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/** Re-uploads paths the server reported missing (their URLs are re-issued if stale). */
|
|
271
|
+
async reupload(paths) {
|
|
272
|
+
const byPath = new Map(this.#s.files.map((f) => [f.path, f]));
|
|
273
|
+
const files = paths.map((p) => byPath.get(p)).filter((f) => f !== undefined);
|
|
274
|
+
for (const f of files)
|
|
275
|
+
this.#done.delete(f.path);
|
|
276
|
+
this.#progress = Math.max(0, this.#progress - files.length);
|
|
277
|
+
await this.uploadAll(files);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Runs the steps after create; any failure carries the created artifact's id, URL and delete token,
|
|
282
|
+
* because the artifact may exist (an answer can be lost after the server published it).
|
|
283
|
+
*/
|
|
284
|
+
export async function afterCreate(created, step) {
|
|
285
|
+
try {
|
|
286
|
+
return await step();
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
const error = err instanceof CliError ? err : new CliError("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
|
|
290
|
+
error.artifact = { id: created.artifact.id, url: created.artifact.url, delete_token: created.delete_token, access_url: created.access_url ?? null };
|
|
291
|
+
throw error;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** The credential for /uploads and /complete: the creating API key, else the delete token. */
|
|
295
|
+
export function manageToken(session) {
|
|
296
|
+
return session.apiKey ?? session.created.delete_token;
|
|
297
|
+
}
|
|
298
|
+
/** Uploads every file and publishes the artifact; returns the published artifact. */
|
|
299
|
+
export async function uploadAndComplete(session) {
|
|
300
|
+
const uploader = new Uploader(session);
|
|
301
|
+
await uploader.uploadAll(session.files);
|
|
302
|
+
for (let call = 1;; call++) {
|
|
303
|
+
try {
|
|
304
|
+
const r = await session.client.call("POST", session.created.upload.complete_url, {
|
|
305
|
+
token: manageToken(session),
|
|
306
|
+
idempotent: true,
|
|
307
|
+
phase: "publish",
|
|
308
|
+
});
|
|
309
|
+
checkArtifact(r?.artifact, "complete");
|
|
310
|
+
return r.artifact;
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
if (!(err instanceof CliError) || err.code !== "upload_incomplete" || call >= MAX_COMPLETE_CALLS)
|
|
314
|
+
throw err;
|
|
315
|
+
const missing = Array.isArray(err.details?.missing) ? err.details.missing.filter((p) => typeof p === "string") : [];
|
|
316
|
+
session.client.log(`complete: ${String(err.details?.missing_count ?? missing.length)} file(s) missing; uploading them again`);
|
|
317
|
+
await uploader.reupload(missing.length ? missing : session.files.map((f) => f.path));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|