@instahost/cli 0.2.0 → 0.3.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/README.md +8 -3
- package/bin/instahost.mjs +2 -1
- package/dist/api-client.js +70 -22
- package/dist/commands/delete.js +1 -2
- package/dist/commands/publish.js +7 -8
- package/dist/commands/share.js +16 -18
- package/dist/config.js +1 -1
- package/dist/errors.js +51 -4
- package/dist/main.js +6 -5
- package/dist/output.js +17 -2
- package/dist/redact.js +6 -3
- package/dist/upload.js +15 -10
- package/package.json +1 -1
- package/src/node-check.mjs +1 -0
package/README.md
CHANGED
|
@@ -107,10 +107,14 @@ Without `--json`, the result goes to stdout (URL, access URL, expiry and the del
|
|
|
107
107
|
`access_token` and `access_url` are set for private files. `delete` prints `{"ok": true, "id": "...", "status": "deleted", "deleted_at": "..."}`. Every failure prints one document:
|
|
108
108
|
|
|
109
109
|
```json
|
|
110
|
-
{"ok": false, "error": {"code": "
|
|
110
|
+
{"ok": false, "error": {"code": "persistent_requires_api_key", "message": "Persistent artifacts need an API key.",
|
|
111
|
+
"fix": "Send an API key as `Authorization: Bearer ihk_…`, or drop `persistent` and set `ttl_seconds`.",
|
|
112
|
+
"docs": "https://instahost.dev/docs/api/#error-persistent_requires_api_key", "exit_code": 4}}
|
|
111
113
|
```
|
|
112
114
|
|
|
113
|
-
|
|
115
|
+
`error.fix` says what to do next. Values it refers to, such as paths or a quota reset time, appear in `error.details` when available. API errors can also include an `error.docs` link to the relevant entry. Human output shows the fix and docs link when available. [API error reference](https://instahost.dev/docs/api/#errors)
|
|
116
|
+
|
|
117
|
+
When a failure happens after the artifact was created, `error.details.artifact` holds `{id, url, delete_token, access_url}`. Use the delete token to remove the artifact.
|
|
114
118
|
|
|
115
119
|
## Exit codes
|
|
116
120
|
|
|
@@ -130,7 +134,8 @@ When a failure happens after the artifact was created, `error.details.artifact`
|
|
|
130
134
|
## Retries and safety
|
|
131
135
|
|
|
132
136
|
- Each upload is retried up to 3 times (after 1, 2 and 4 s) on network errors, 429 and 5xx. A URL close to expiry is refreshed before use, and a 403 gets a fresh URL once per file.
|
|
133
|
-
-
|
|
137
|
+
- API calls retry up to 3 times on network errors, 502, 503 and 504, and on 429 `rate_limited` after `Retry-After` (up to 60 s).
|
|
138
|
+
- `share` and `publish` send the same key and body on every attempt to create an artifact. A retry within the replay window can recover the original response. Create also retries on 500 and can retry a quota refusal after a network error or 5xx. When every request times out, a create can take about two minutes to report failure. [Retrying a create](https://instahost.dev/docs/api/#retry-create)
|
|
134
139
|
- Credentials are sent only to the API origin. Upload URLs must be `https`, and the API's own follow-up URLs must be on its origin. Redirects are refused.
|
|
135
140
|
|
|
136
141
|
## Programmatic use
|
package/bin/instahost.mjs
CHANGED
|
@@ -19,7 +19,8 @@ try {
|
|
|
19
19
|
// A damaged or partial install (dist/ missing or unreadable): still exactly one answer.
|
|
20
20
|
const code = (err && typeof err === "object" && "code" in err && typeof err.code === "string") ? err.code : "unknown";
|
|
21
21
|
const message = `The CLI could not load its compiled files (${code}); reinstall it: npx -y @instahost/cli@latest, or npm i -g @instahost/cli.`;
|
|
22
|
-
|
|
22
|
+
const fix = "Reinstall the CLI with `npx -y @instahost/cli@latest` or `npm i -g @instahost/cli`.";
|
|
23
|
+
if (json) process.stdout.write(`${JSON.stringify({ ok: false, error: { code: "cli_load_failed", message, details: { reason: code }, fix, exit_code: 1 } })}\n`);
|
|
23
24
|
else process.stderr.write(`instahost: ${message}\n`);
|
|
24
25
|
process.exit(1);
|
|
25
26
|
}
|
package/dist/api-client.js
CHANGED
|
@@ -4,13 +4,14 @@
|
|
|
4
4
|
// (uploads_url, complete_url) must be on that origin too.
|
|
5
5
|
// - API calls time out after 30 s. Idempotent calls (uploads, complete, delete) are retried 3
|
|
6
6
|
// times on network errors and 502/503/504 (1 s, 2 s, 4 s apart) and on 429 after Retry-After.
|
|
7
|
-
// Create
|
|
7
|
+
// Create retries with one key and body, also on 500 and on quota refusals after a lost
|
|
8
|
+
// or 5xx answer. The key stays internal to this invocation.
|
|
8
9
|
import { USER_AGENT } from "./config.js";
|
|
9
|
-
import { CliError, EXIT
|
|
10
|
+
import { CliError, EXIT } from "./errors.js";
|
|
10
11
|
import { describeUrl, redact } from "./redact.js";
|
|
11
12
|
export const API_TIMEOUT_MS = 30_000;
|
|
12
|
-
export const RETRIES = 3;
|
|
13
13
|
export const BACKOFF_SECONDS = [1, 2, 4];
|
|
14
|
+
export const RETRIES = BACKOFF_SECONDS.length;
|
|
14
15
|
/** A Retry-After longer than this is not waited for; the 429 is reported instead. */
|
|
15
16
|
export const MAX_RETRY_AFTER_SECONDS = 60;
|
|
16
17
|
const RETRYABLE_STATUS = new Set([502, 503, 504]);
|
|
@@ -33,7 +34,36 @@ function failureReason(err) {
|
|
|
33
34
|
return "unknown";
|
|
34
35
|
if (err.name === "TimeoutError")
|
|
35
36
|
return "timeout";
|
|
36
|
-
|
|
37
|
+
const code = err.cause?.code;
|
|
38
|
+
return typeof code === "string" ? code : err.name;
|
|
39
|
+
}
|
|
40
|
+
function createErrorGuidance(code) {
|
|
41
|
+
switch (code) {
|
|
42
|
+
case "internal_error":
|
|
43
|
+
return { fix: "Run the command again later, and report it with the time of the request if the error persists." };
|
|
44
|
+
case "gone":
|
|
45
|
+
return {
|
|
46
|
+
message: "The artifact from the previous create attempt or its upload URLs have expired, or the artifact was deleted or blocked.",
|
|
47
|
+
fix: "Run the command again to create a new artifact.",
|
|
48
|
+
};
|
|
49
|
+
case "artifact_not_pending":
|
|
50
|
+
return {
|
|
51
|
+
message: "The artifact from the previous create attempt is already published or failed.",
|
|
52
|
+
fix: "Run the command again to create a new artifact.",
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function errorDocs(value, apiOrigin) {
|
|
57
|
+
if (typeof value !== "string")
|
|
58
|
+
return;
|
|
59
|
+
try {
|
|
60
|
+
const url = new URL(value);
|
|
61
|
+
if (url.origin === apiOrigin && (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password)
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// An invalid docs link can be omitted without losing the original error.
|
|
66
|
+
}
|
|
37
67
|
}
|
|
38
68
|
export class ApiClient {
|
|
39
69
|
apiUrl;
|
|
@@ -56,7 +86,7 @@ export class ApiClient {
|
|
|
56
86
|
resolve(pathOrUrl) {
|
|
57
87
|
const url = new URL(pathOrUrl, this.apiUrl);
|
|
58
88
|
if (url.origin !== this.apiUrl) {
|
|
59
|
-
throw
|
|
89
|
+
throw CliError.local("unsafe_url", "The API returned a URL on another origin; refusing to send credentials there.", EXIT.network, { url: describeUrl(url.href) });
|
|
60
90
|
}
|
|
61
91
|
return url;
|
|
62
92
|
}
|
|
@@ -67,58 +97,76 @@ export class ApiClient {
|
|
|
67
97
|
headers["content-type"] = "application/json";
|
|
68
98
|
if (options.token)
|
|
69
99
|
headers.authorization = `Bearer ${options.token}`;
|
|
100
|
+
const isCreate = options.phase === "create";
|
|
101
|
+
const key = isCreate ? options.idempotencyKey : undefined;
|
|
102
|
+
if (key)
|
|
103
|
+
headers["idempotency-key"] = key;
|
|
70
104
|
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
|
|
71
|
-
const
|
|
72
|
-
|
|
105
|
+
const redactKey = (value) => key ? value.replaceAll(key, "***") : value;
|
|
106
|
+
let ambiguousCreate = false;
|
|
107
|
+
for (let attempt = 0;; attempt++) {
|
|
108
|
+
const backoff = BACKOFF_SECONDS[attempt];
|
|
73
109
|
const started = Date.now();
|
|
74
110
|
let res;
|
|
75
111
|
let text;
|
|
76
112
|
try {
|
|
77
113
|
// The body read is guarded too: a connection cut or the timeout during the body is a
|
|
78
|
-
// network failure like any other
|
|
114
|
+
// network failure like any other.
|
|
79
115
|
res = await this.#fetch(url, { method, headers, body, redirect: "error", signal: AbortSignal.timeout(API_TIMEOUT_MS) });
|
|
80
116
|
text = await res.text();
|
|
81
117
|
}
|
|
82
118
|
catch (err) {
|
|
83
|
-
const reason = failureReason(err);
|
|
119
|
+
const reason = redactKey(failureReason(err));
|
|
84
120
|
this.log(`api ${method} ${url.pathname} failed (${reason})`);
|
|
85
|
-
if (
|
|
86
|
-
|
|
121
|
+
if (backoff !== undefined) {
|
|
122
|
+
ambiguousCreate = isCreate;
|
|
123
|
+
await this.#sleep(backoff);
|
|
87
124
|
continue;
|
|
88
125
|
}
|
|
89
|
-
throw
|
|
126
|
+
throw CliError.local("network_error", `Could not reach the API at ${this.apiUrl}.`, EXIT.network, { reason });
|
|
90
127
|
}
|
|
91
|
-
|
|
128
|
+
const replayed = isCreate && res.status === 201 && res.headers.get("idempotent-replayed") === "true";
|
|
129
|
+
this.log(`api ${method} ${url.pathname} -> ${res.status} (${Date.now() - started} ms)${replayed ? " (replayed)" : ""}`);
|
|
92
130
|
let parsed = null;
|
|
93
131
|
try {
|
|
94
|
-
parsed = text ? JSON.parse(text) : null;
|
|
132
|
+
parsed = text ? JSON.parse(res.ok ? text : redactKey(text)) : null;
|
|
95
133
|
}
|
|
96
134
|
catch { }
|
|
97
135
|
if (res.ok) {
|
|
98
136
|
if (parsed === null || typeof parsed !== "object")
|
|
99
|
-
throw
|
|
137
|
+
throw CliError.local("bad_response", `The API answered ${res.status} without a JSON body.`, EXIT.network, undefined, res.status);
|
|
100
138
|
return parsed;
|
|
101
139
|
}
|
|
102
140
|
const envelope = parsed?.error;
|
|
103
141
|
const code = typeof envelope?.code === "string" ? envelope.code : `http_${res.status}`;
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
142
|
+
const retryAfter = retryAfterSeconds(res.headers.get("retry-after"));
|
|
143
|
+
if (backoff !== undefined) {
|
|
144
|
+
if (RETRYABLE_STATUS.has(res.status) || (isCreate && res.status === 500)) {
|
|
145
|
+
ambiguousCreate = isCreate;
|
|
146
|
+
await this.#sleep(backoff);
|
|
107
147
|
continue;
|
|
108
148
|
}
|
|
109
149
|
if (res.status === 429 && code === "rate_limited") {
|
|
110
|
-
const wait =
|
|
150
|
+
const wait = retryAfter ?? backoff;
|
|
111
151
|
if (wait <= MAX_RETRY_AFTER_SECONDS) {
|
|
112
152
|
this.log(`api rate limited; retrying in ${wait} s`);
|
|
113
153
|
await this.#sleep(wait);
|
|
114
154
|
continue;
|
|
115
155
|
}
|
|
116
156
|
}
|
|
157
|
+
// The first attempt may have taken the last quota slot before its response arrived.
|
|
158
|
+
// Retry inside the replay window rather than waiting for the daily quota reset.
|
|
159
|
+
if (res.status === 429 && code === "quota_exceeded" && ambiguousCreate) {
|
|
160
|
+
await this.#sleep(backoff);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
117
163
|
}
|
|
118
|
-
const
|
|
164
|
+
const override = isCreate ? createErrorGuidance(code) : undefined;
|
|
165
|
+
const message = override?.message ?? (typeof envelope?.message === "string" ? envelope.message : `The API answered ${res.status}.`);
|
|
166
|
+
const apiFix = envelope?.fix;
|
|
167
|
+
const fix = override?.fix ?? (typeof apiFix === "string" && apiFix.length > 0 && apiFix.length <= 500 ? apiFix : undefined);
|
|
119
168
|
const details = envelope?.details && typeof envelope.details === "object" ? envelope.details : undefined;
|
|
120
|
-
|
|
121
|
-
throw new CliError(code, redact(message), exitCodeForApiError(res.status, code, options.phase), retryAfter === null ? details : { ...details, retry_after_seconds: retryAfter }, res.status);
|
|
169
|
+
throw CliError.api(code, message, res.status, options.phase, retryAfter === null ? details : { ...details, retry_after_seconds: retryAfter }, { fix, docs: errorDocs(envelope?.docs, this.apiUrl) });
|
|
122
170
|
}
|
|
123
171
|
}
|
|
124
172
|
}
|
package/dist/commands/delete.js
CHANGED
|
@@ -32,10 +32,9 @@ export async function deleteArtifact(ctx, options) {
|
|
|
32
32
|
throw usageError("delete needs the artifact's delete token (--token or INSTAHOST_DELETE_TOKEN) or the owner's API key.");
|
|
33
33
|
const r = await ctx.client.call("DELETE", `/v1/artifacts/${id}`, {
|
|
34
34
|
token: credential,
|
|
35
|
-
idempotent: true,
|
|
36
35
|
phase: "delete",
|
|
37
36
|
});
|
|
38
37
|
if (typeof r?.artifact?.id !== "string" || typeof r.artifact.status !== "string")
|
|
39
|
-
throw
|
|
38
|
+
throw CliError.local("bad_response", "The API's answer to delete has no artifact.", EXIT.network);
|
|
40
39
|
return { ok: true, id: r.artifact.id, status: r.artifact.status, deleted_at: r.artifact.deleted_at ?? null };
|
|
41
40
|
}
|
package/dist/commands/publish.js
CHANGED
|
@@ -6,7 +6,7 @@ import { sep } from "node:path";
|
|
|
6
6
|
import { inputError } from "../errors.js";
|
|
7
7
|
import { sensitiveRule } from "../vendor/paths.js";
|
|
8
8
|
import { lifetimeFields } from "../ttl.js";
|
|
9
|
-
import { afterCreate,
|
|
9
|
+
import { afterCreate, createArtifact, uploadAndComplete } from "../upload.js";
|
|
10
10
|
import { findRootAbsoluteReferences, walkSite } from "../walk.js";
|
|
11
11
|
const MAX_WARNING_PATHS = 20;
|
|
12
12
|
async function prepareSite(options) {
|
|
@@ -57,13 +57,12 @@ export async function previewPublish(options) {
|
|
|
57
57
|
}
|
|
58
58
|
export async function publish(ctx, options) {
|
|
59
59
|
const walked = await prepareSite(options);
|
|
60
|
-
const created = await ctx.client
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
});
|
|
66
|
-
checkCreated(created);
|
|
60
|
+
const created = await createArtifact(ctx.client, {
|
|
61
|
+
type: "site",
|
|
62
|
+
access: options.access,
|
|
63
|
+
...lifetimeFields(options.lifetime),
|
|
64
|
+
files: walked.files.map((f) => ({ path: f.path, size: f.size, md5: f.md5 })),
|
|
65
|
+
}, ctx.apiKey);
|
|
67
66
|
const artifact = await afterCreate(created, () => uploadAndComplete({
|
|
68
67
|
client: ctx.client,
|
|
69
68
|
created,
|
package/dist/commands/share.js
CHANGED
|
@@ -6,7 +6,7 @@ import { lstat, realpath } from "node:fs/promises";
|
|
|
6
6
|
import { basename, resolve, sep } from "node:path";
|
|
7
7
|
import { CliError, EXIT, inputError } from "../errors.js";
|
|
8
8
|
import { lifetimeFields } from "../ttl.js";
|
|
9
|
-
import { afterCreate,
|
|
9
|
+
import { afterCreate, createArtifact, uploadAndComplete } from "../upload.js";
|
|
10
10
|
import { sensitiveRule, validatePath } from "../vendor/paths.js";
|
|
11
11
|
import { hashFile } from "../walk.js";
|
|
12
12
|
function refuseSensitive(label, path) {
|
|
@@ -47,24 +47,22 @@ export async function share(ctx, options) {
|
|
|
47
47
|
const file = { path: name, size, md5 };
|
|
48
48
|
if (options.contentType !== undefined)
|
|
49
49
|
file.content_type = options.contentType;
|
|
50
|
-
const created = await ctx.client
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
50
|
+
const created = await createArtifact(ctx.client, {
|
|
51
|
+
type: "file", access: options.access, ...lifetimeFields(options.lifetime), files: [file],
|
|
52
|
+
}, ctx.apiKey);
|
|
53
|
+
const artifact = await afterCreate(created, async () => {
|
|
54
|
+
if (!created.upload.files.length)
|
|
55
|
+
throw CliError.local("bad_response", "The API returned no upload URL.", EXIT.network);
|
|
56
|
+
return uploadAndComplete({
|
|
57
|
+
client: ctx.client,
|
|
58
|
+
created,
|
|
59
|
+
apiKey: ctx.apiKey,
|
|
60
|
+
files: [{ path: name, absPath: options.file, size, md5, dev, ino }],
|
|
61
|
+
concurrency: 1,
|
|
62
|
+
onProgress: ctx.onProgress,
|
|
63
|
+
fetch: ctx.fetch,
|
|
64
|
+
});
|
|
55
65
|
});
|
|
56
|
-
checkCreated(created);
|
|
57
|
-
if (!created.upload.files.length)
|
|
58
|
-
throw new CliError("bad_response", "The API returned no upload URL.", EXIT.network);
|
|
59
|
-
const artifact = await afterCreate(created, () => uploadAndComplete({
|
|
60
|
-
client: ctx.client,
|
|
61
|
-
created,
|
|
62
|
-
apiKey: ctx.apiKey,
|
|
63
|
-
files: [{ path: name, absPath: options.file, size, md5, dev, ino }],
|
|
64
|
-
concurrency: 1,
|
|
65
|
-
onProgress: ctx.onProgress,
|
|
66
|
-
fetch: ctx.fetch,
|
|
67
|
-
}));
|
|
68
66
|
return {
|
|
69
67
|
ok: true,
|
|
70
68
|
id: artifact.id,
|
package/dist/config.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Precedence: flag, then environment, then DEFAULT_API_URL, the production API origin. Empty
|
|
3
3
|
// means the CLI asks for an API URL.
|
|
4
4
|
import { usageError } from "./errors.js";
|
|
5
|
-
export const VERSION = "0.
|
|
5
|
+
export const VERSION = "0.3.0";
|
|
6
6
|
/**
|
|
7
7
|
* The production API origin. The service's deploy preflight refuses to deploy an API origin that
|
|
8
8
|
* differs from this value in the CLI version it pins, so changing the API domain needs a CLI release
|
package/dist/errors.js
CHANGED
|
@@ -12,32 +12,78 @@ export const EXIT = {
|
|
|
12
12
|
publishFailed: 8,
|
|
13
13
|
notFound: 9,
|
|
14
14
|
};
|
|
15
|
+
const REPORT_URL = "https://github.com/instahost-dev/instahost/issues";
|
|
16
|
+
const UPDATE_FIX = "Try the latest CLI (`npx -y @instahost/cli@latest`), then report the error at " + REPORT_URL + " if it persists.";
|
|
17
|
+
export const LOCAL_FIX = {
|
|
18
|
+
usage: "Correct the command using the options listed by `npx -y @instahost/cli --help`.",
|
|
19
|
+
internal_error: `Run the command again, then report the error at ${REPORT_URL} with the CLI version if it persists.`,
|
|
20
|
+
file_not_found: "Check the path, then run the command again.",
|
|
21
|
+
not_a_file: "Pass a regular file to `share`, or use `publish` for a directory.",
|
|
22
|
+
not_a_directory: "Pass a directory to `publish`, or share a single file with `share`.",
|
|
23
|
+
unreadable_file: "Make the file readable, then run the command again.",
|
|
24
|
+
unreadable_directory: "Make the directory readable, then run the command again.",
|
|
25
|
+
symlink_refused: "Pass the real file instead of a symbolic link.",
|
|
26
|
+
sensitive_file: "Leave this file out, because its name or location looks like a credential or VCS data.",
|
|
27
|
+
invalid_path: "Rename the files in `details.paths`, or pass `--name` when sharing a single file.",
|
|
28
|
+
duplicate_path: "Rename one of the files in `details.paths` so that the two names differ.",
|
|
29
|
+
missing_index: "Add an `index.html` at the root of the directory, or share a single file with `share`.",
|
|
30
|
+
empty_directory: "Publish the directory that holds the built site and its `index.html`.",
|
|
31
|
+
walk_too_many_files: "Publish a smaller directory, such as the build output only.",
|
|
32
|
+
file_changed: "Run the command again once the file is no longer changing.",
|
|
33
|
+
network_error: "Check the network connection, then run the command again.",
|
|
34
|
+
upload_failed: "Run the command again later.",
|
|
35
|
+
bad_response: UPDATE_FIX,
|
|
36
|
+
unsafe_url: UPDATE_FIX,
|
|
37
|
+
};
|
|
38
|
+
const API_FALLBACK_FIX = {
|
|
39
|
+
[EXIT.internal]: LOCAL_FIX.internal_error,
|
|
40
|
+
[EXIT.usage]: LOCAL_FIX.usage,
|
|
41
|
+
[EXIT.localInput]: "Check the local input described in the message, then run the command again.",
|
|
42
|
+
[EXIT.auth]: "Check the API key or delete token, then run the command again.",
|
|
43
|
+
[EXIT.rejected]: "Change the request as the message says, then run the command again.",
|
|
44
|
+
[EXIT.rateLimited]: "Wait the number of seconds in `details.retry_after_seconds` if set, then run the command again.",
|
|
45
|
+
[EXIT.network]: LOCAL_FIX.upload_failed,
|
|
46
|
+
[EXIT.publishFailed]: "Run the command again to publish a new artifact.",
|
|
47
|
+
[EXIT.notFound]: "Check the artifact id or URL.",
|
|
48
|
+
};
|
|
15
49
|
export class CliError extends Error {
|
|
16
50
|
name = "CliError";
|
|
17
51
|
code;
|
|
18
52
|
exitCode;
|
|
19
53
|
details;
|
|
54
|
+
fix;
|
|
55
|
+
docs;
|
|
20
56
|
/** HTTP status of the API answer behind this error, if any. */
|
|
21
57
|
status;
|
|
22
58
|
/** Set when the failure came after create: the artifact may exist (it may even be published). */
|
|
23
59
|
artifact;
|
|
24
|
-
constructor(code, message, exitCode, details, status) {
|
|
60
|
+
constructor(code, message, exitCode, fix, details, status, docs) {
|
|
25
61
|
super(message);
|
|
26
62
|
this.code = code;
|
|
27
63
|
this.exitCode = exitCode;
|
|
28
64
|
this.details = details;
|
|
65
|
+
this.fix = fix;
|
|
66
|
+
this.docs = docs;
|
|
29
67
|
this.status = status;
|
|
30
68
|
}
|
|
69
|
+
static local(code, message, exitCode, details, status) {
|
|
70
|
+
return new CliError(code, message, exitCode, LOCAL_FIX[code], details, status);
|
|
71
|
+
}
|
|
72
|
+
static api(code, message, status, phase, details, guidance) {
|
|
73
|
+
const exitCode = apiFailureExitCode(status, code, phase);
|
|
74
|
+
const fix = status === 429 && code === "rate_limited" ? API_FALLBACK_FIX[EXIT.rateLimited] : guidance.fix;
|
|
75
|
+
return new CliError(code, message, exitCode, fix ?? API_FALLBACK_FIX[exitCode], details, status, guidance.docs);
|
|
76
|
+
}
|
|
31
77
|
}
|
|
32
|
-
export const usageError = (message, details) =>
|
|
33
|
-
export const inputError = (code, message, details) =>
|
|
78
|
+
export const usageError = (message, details) => CliError.local("usage", message, EXIT.usage, details);
|
|
79
|
+
export const inputError = (code, message, details) => CliError.local(code, message, EXIT.localInput, details);
|
|
34
80
|
/** API error codes that end a publication (exit 8) wherever they appear in the publish phase. */
|
|
35
81
|
const PUBLICATION_CODES = new Set(["upload_mismatch", "upload_incomplete", "artifact_failed", "artifact_not_pending", "upload_url_limit", "complete_attempt_limit", "gone"]);
|
|
36
82
|
/**
|
|
37
83
|
* Exit code for an error envelope from the API. Order matters: 429 and 401/403 win over the phase,
|
|
38
84
|
* 404 is not found, 5xx is a server failure.
|
|
39
85
|
*/
|
|
40
|
-
|
|
86
|
+
function apiFailureExitCode(status, code, phase) {
|
|
41
87
|
if (status === 429)
|
|
42
88
|
return EXIT.rateLimited;
|
|
43
89
|
if (status === 401 || status === 403)
|
|
@@ -52,3 +98,4 @@ export function exitCodeForApiError(status, code, phase) {
|
|
|
52
98
|
return EXIT.rejected;
|
|
53
99
|
return EXIT.internal;
|
|
54
100
|
}
|
|
101
|
+
export const exitCodeForApiError = apiFailureExitCode;
|
package/dist/main.js
CHANGED
|
@@ -32,6 +32,7 @@ and lists them under "skipped". Sites must use relative URLs (Vite: base: "./").
|
|
|
32
32
|
publish --dry-run lists what would be published or skipped without contacting InstaHost.
|
|
33
33
|
delete uses --token, else --api-key, else INSTAHOST_DELETE_TOKEN, else INSTAHOST_API_KEY; the
|
|
34
34
|
environment keeps the token out of the process list.
|
|
35
|
+
On a failure, error.fix in the JSON output says what to do next.
|
|
35
36
|
|
|
36
37
|
Exit codes: 0 ok, 1 internal error, 2 usage, 3 local input (missing file, no index.html, invalid or
|
|
37
38
|
sensitive name), 4 authentication or authorization (401, 403), 5 rejected by the server (400, 413,
|
|
@@ -168,15 +169,15 @@ async function run(argv, deps, streams, json) {
|
|
|
168
169
|
const progress = { open: false };
|
|
169
170
|
/**
|
|
170
171
|
* Last resort for a real process: an error that escapes main() still ends as one JSON document
|
|
171
|
-
* (or
|
|
172
|
+
* (or a human-readable error) and exit code 1.
|
|
172
173
|
*/
|
|
173
174
|
function installCrashHandlers(argv, streams) {
|
|
174
175
|
const crash = (err) => {
|
|
175
|
-
const
|
|
176
|
+
const error = CliError.local("internal_error", `Unexpected error: ${err instanceof Error ? err.name : "unknown"}`, EXIT.internal);
|
|
176
177
|
if (argv.includes("--json"))
|
|
177
|
-
printJson(streams,
|
|
178
|
+
printJson(streams, errorDocument(error));
|
|
178
179
|
else
|
|
179
|
-
streams
|
|
180
|
+
printHumanError(streams, error);
|
|
180
181
|
process.exit(EXIT.internal);
|
|
181
182
|
};
|
|
182
183
|
process.once("uncaughtException", crash);
|
|
@@ -194,7 +195,7 @@ export async function main(argv, deps = {}) {
|
|
|
194
195
|
streams.stderr("\n");
|
|
195
196
|
progress.open = false;
|
|
196
197
|
}
|
|
197
|
-
const cliError = err instanceof CliError ? err :
|
|
198
|
+
const cliError = err instanceof CliError ? err : CliError.local("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
|
|
198
199
|
if (json)
|
|
199
200
|
printJson(streams, errorDocument(cliError));
|
|
200
201
|
else
|
package/dist/output.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { redact } from "./redact.js";
|
|
1
|
+
import { redact, redactCredentials } from "./redact.js";
|
|
2
|
+
const ARTIFACT_FIX = "The artifact in `details.artifact` may exist: delete it with its `delete_token`.";
|
|
2
3
|
/** Redacts every string inside a JSON-like value (never the serialised text, which it could corrupt). */
|
|
3
4
|
export function redactValue(value) {
|
|
4
5
|
if (typeof value === "string")
|
|
@@ -17,7 +18,18 @@ export function errorDocument(err) {
|
|
|
17
18
|
let details = err.details && Object.keys(err.details).length ? redactValue(err.details) : undefined;
|
|
18
19
|
if (err.artifact)
|
|
19
20
|
details = { ...details, artifact: { ...err.artifact } };
|
|
20
|
-
|
|
21
|
+
const fix = redactCredentials(err.fix) + (err.artifact ? ` ${ARTIFACT_FIX}` : "");
|
|
22
|
+
return {
|
|
23
|
+
ok: false,
|
|
24
|
+
error: {
|
|
25
|
+
code: err.code,
|
|
26
|
+
message: redact(err.message),
|
|
27
|
+
...(details ? { details } : {}),
|
|
28
|
+
fix,
|
|
29
|
+
...(err.docs ? { docs: redactCredentials(err.docs) } : {}),
|
|
30
|
+
exit_code: err.exitCode,
|
|
31
|
+
},
|
|
32
|
+
};
|
|
21
33
|
}
|
|
22
34
|
/**
|
|
23
35
|
* The delete command printed in human output. It names the scoped package on purpose: most users run
|
|
@@ -80,6 +92,9 @@ export function printHumanError(streams, err) {
|
|
|
80
92
|
}
|
|
81
93
|
if (typeof details.reason === "string" && !paths.length && !err.message.includes(details.reason))
|
|
82
94
|
lines[0] += ` (${t(details.reason)})`;
|
|
95
|
+
lines.push(` fix: ${terminalSafe(redactCredentials(err.fix))}`);
|
|
96
|
+
if (err.docs)
|
|
97
|
+
lines.push(` docs: ${terminalSafe(redactCredentials(err.docs))}`);
|
|
83
98
|
if (err.artifact) {
|
|
84
99
|
const a = err.artifact;
|
|
85
100
|
lines.push(`instahost: the artifact may exist (${t(a.url)}); delete it with: ${DELETE_COMMAND} ${a.id} --token ${terminalSafe(a.delete_token)}`);
|
package/dist/redact.js
CHANGED
|
@@ -5,12 +5,15 @@ const TOKEN = /\bih([dak])_[A-Za-z0-9_-]+/g;
|
|
|
5
5
|
const SIGNED_PARAM = /\b(X-Amz-(?:Signature|Credential|Security-Token))=[^&\s"']+/gi;
|
|
6
6
|
const TOKEN_PARAM = /([?&]token=)[^&\s"']+/gi;
|
|
7
7
|
const BEARER = /\b(Bearer\s+)[^\s"']+/gi;
|
|
8
|
-
|
|
8
|
+
/** Masks credentials without swallowing placeholders in guidance such as `Bearer <token>`. */
|
|
9
|
+
export function redactCredentials(text) {
|
|
9
10
|
return text
|
|
10
11
|
.replace(TOKEN, (_m, kind) => `ih${kind}_***`)
|
|
11
12
|
.replace(SIGNED_PARAM, "$1=***")
|
|
12
|
-
.replace(TOKEN_PARAM, "$1***")
|
|
13
|
-
|
|
13
|
+
.replace(TOKEN_PARAM, "$1***");
|
|
14
|
+
}
|
|
15
|
+
export function redact(text) {
|
|
16
|
+
return redactCredentials(text).replace(BEARER, "$1***");
|
|
14
17
|
}
|
|
15
18
|
/** A URL safe for diagnostics: origin and path only (no query string, which may hold a signature). */
|
|
16
19
|
export function describeUrl(url) {
|
package/dist/upload.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
// (the local R2 emulator); they never get an Authorization header.
|
|
14
14
|
// - /complete answering 409 upload_incomplete re-uploads details.missing, then completes again, at
|
|
15
15
|
// most 3 complete calls in all (the server allows MAX_COMPLETE_ATTEMPTS = 4).
|
|
16
|
+
import { randomUUID } from "node:crypto";
|
|
16
17
|
import { openAsBlob } from "node:fs";
|
|
17
18
|
import { lstat } from "node:fs/promises";
|
|
18
19
|
import { BACKOFF_SECONDS, RETRIES } from "./api-client.js";
|
|
@@ -39,12 +40,12 @@ export function checkUploadUrl(raw, apiUrl) {
|
|
|
39
40
|
url = new URL(raw);
|
|
40
41
|
}
|
|
41
42
|
catch {
|
|
42
|
-
throw
|
|
43
|
+
throw CliError.local("unsafe_url", "The API returned an invalid upload URL.", EXIT.network);
|
|
43
44
|
}
|
|
44
45
|
const api = new URL(apiUrl);
|
|
45
46
|
const localHttp = url.protocol === "http:" && isLoopbackHost(url.hostname) && api.protocol === "http:" && isLoopbackHost(api.hostname);
|
|
46
47
|
if (url.protocol !== "https:" && !localHttp) {
|
|
47
|
-
throw
|
|
48
|
+
throw CliError.local("unsafe_url", "The API returned an upload URL that is not https.", EXIT.network, { url: describeUrl(raw) });
|
|
48
49
|
}
|
|
49
50
|
return url;
|
|
50
51
|
}
|
|
@@ -56,7 +57,7 @@ export function checkBatch(batch, where) {
|
|
|
56
57
|
Array.isArray(b.files) &&
|
|
57
58
|
b.files.every((f) => f && typeof f.path === "string" && typeof f.url === "string" && f.method === "PUT" && f.headers !== null && typeof f.headers === "object");
|
|
58
59
|
if (!ok)
|
|
59
|
-
throw
|
|
60
|
+
throw CliError.local("bad_response", `The API's answer to ${where} has no valid upload instructions.`, EXIT.network);
|
|
60
61
|
}
|
|
61
62
|
/** The fields read from a create answer (batch_size must be at least 1, or batching never ends). */
|
|
62
63
|
export function checkCreated(created) {
|
|
@@ -70,13 +71,19 @@ export function checkCreated(created) {
|
|
|
70
71
|
typeof u.uploads_url === "string" &&
|
|
71
72
|
typeof u.complete_url === "string";
|
|
72
73
|
if (!ok)
|
|
73
|
-
throw
|
|
74
|
+
throw CliError.local("bad_response", "The API's answer to create is incomplete.", EXIT.network);
|
|
75
|
+
}
|
|
76
|
+
/** Give each invocation one create key for the original request and any retries. */
|
|
77
|
+
export async function createArtifact(client, body, token) {
|
|
78
|
+
const created = await client.call("POST", "/v1/artifacts", { body, token, phase: "create", idempotencyKey: randomUUID() });
|
|
79
|
+
checkCreated(created);
|
|
80
|
+
return created;
|
|
74
81
|
}
|
|
75
82
|
/** The fields read from a published artifact. */
|
|
76
83
|
export function checkArtifact(artifact, where) {
|
|
77
84
|
const a = artifact;
|
|
78
85
|
if (!a || typeof a.id !== "string" || typeof a.url !== "string")
|
|
79
|
-
throw
|
|
86
|
+
throw CliError.local("bad_response", `The API's answer to ${where} has no artifact.`, EXIT.network);
|
|
80
87
|
}
|
|
81
88
|
class Uploader {
|
|
82
89
|
#s;
|
|
@@ -121,7 +128,6 @@ class Uploader {
|
|
|
121
128
|
const r = await this.#s.client.call("POST", this.#s.created.upload.uploads_url, {
|
|
122
129
|
body: { paths: paths.slice(i, i + size) },
|
|
123
130
|
token: this.#token,
|
|
124
|
-
idempotent: true,
|
|
125
131
|
phase: "publish",
|
|
126
132
|
});
|
|
127
133
|
checkBatch(r?.upload, "/uploads");
|
|
@@ -213,7 +219,7 @@ class Uploader {
|
|
|
213
219
|
for (;;) {
|
|
214
220
|
const cached = this.#cache.get(file.path);
|
|
215
221
|
if (!cached)
|
|
216
|
-
throw
|
|
222
|
+
throw CliError.local("bad_response", `The API returned no upload URL for ${file.path}.`, EXIT.network, { path: file.path });
|
|
217
223
|
// A URL about to expire is replaced before use (once: near the end of the upload window the
|
|
218
224
|
// server only issues short-lived URLs, which are then used as they are).
|
|
219
225
|
if (!refreshedBeforeUse && this.#stale(file.path)) {
|
|
@@ -264,7 +270,7 @@ class Uploader {
|
|
|
264
270
|
throw inputError("file_changed", `${file.path} changed since it was hashed (storage refused its checksum); try again.`, { path: file.path });
|
|
265
271
|
}
|
|
266
272
|
const reason = status === 0 ? `network error (${detail})` : `HTTP ${status}${detail ? ` ${detail}` : ""}`;
|
|
267
|
-
throw
|
|
273
|
+
throw CliError.local("upload_failed", `Uploading ${file.path} failed: ${reason}.`, EXIT.network, { path: file.path, status: status || null, s3_code: status ? detail : null });
|
|
268
274
|
}
|
|
269
275
|
}
|
|
270
276
|
/** Re-uploads paths the server reported missing (their URLs are re-issued if stale). */
|
|
@@ -286,7 +292,7 @@ export async function afterCreate(created, step) {
|
|
|
286
292
|
return await step();
|
|
287
293
|
}
|
|
288
294
|
catch (err) {
|
|
289
|
-
const error = err instanceof CliError ? err :
|
|
295
|
+
const error = err instanceof CliError ? err : CliError.local("internal_error", `Unexpected error: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`, EXIT.internal);
|
|
290
296
|
error.artifact = { id: created.artifact.id, url: created.artifact.url, delete_token: created.delete_token, access_url: created.access_url ?? null };
|
|
291
297
|
throw error;
|
|
292
298
|
}
|
|
@@ -303,7 +309,6 @@ export async function uploadAndComplete(session) {
|
|
|
303
309
|
try {
|
|
304
310
|
const r = await session.client.call("POST", session.created.upload.complete_url, {
|
|
305
311
|
token: manageToken(session),
|
|
306
|
-
idempotent: true,
|
|
307
312
|
phase: "publish",
|
|
308
313
|
});
|
|
309
314
|
checkArtifact(r?.artifact, "complete");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@instahost/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Instant hosting and sharing for AI agents: share a file or publish a static site and get an HTTPS URL. The unscoped npm package named instahost is unrelated.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"hosting",
|
package/src/node-check.mjs
CHANGED
|
@@ -28,6 +28,7 @@ export function tooOldDocument(version) {
|
|
|
28
28
|
code: "node_too_old",
|
|
29
29
|
message: `Node.js >= ${MIN_NODE[0]} is required (this is ${version}).`,
|
|
30
30
|
details: { required: `>=${MIN_NODE.join(".")}.0`, found: String(version) },
|
|
31
|
+
fix: `Run the CLI with Node.js ${MIN_NODE[0]} or later.`,
|
|
31
32
|
exit_code: 2,
|
|
32
33
|
},
|
|
33
34
|
};
|