@instahost/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The InstaHost contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,126 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @instahost/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Instant hosting and sharing for AI agents. `share` a file or `publish` a built static site and get back an HTTPS URL with an access mode and a lifetime. No account and no login are needed for links that last up to 7 days. The service runs at [instahost.dev](https://instahost.dev).
|
|
4
|
+
|
|
5
|
+
> The npm package named `instahost` (without the `@instahost/` scope) is unrelated to this project. Do not install it. Use `@instahost/cli`.
|
|
6
|
+
|
|
7
|
+
Requires Node.js 20 or later. The package has no runtime dependencies.
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
echo 'Hello from InstaHost' > hello.txt
|
|
13
|
+
mkdir -p hello-site && echo 'Hello from InstaHost' > hello-site/index.html
|
|
14
|
+
npx -y @instahost/cli share hello.txt --ttl 1h --json
|
|
15
|
+
npx -y @instahost/cli publish hello-site --ttl 1h --json
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Or install it once:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm i -g @instahost/cli
|
|
22
|
+
instahost publish ./dist --json
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Commands
|
|
26
|
+
|
|
27
|
+
```text
|
|
28
|
+
instahost share <file> [--ttl 24h] [--access unlisted|public|private] [--name <filename>] [--content-type <type>]
|
|
29
|
+
instahost publish <dir> [--ttl 24h] [--access unlisted|public] [--include-dotfiles] [--concurrency 6]
|
|
30
|
+
instahost delete <id|url> [--token <ihd_...>]
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npx -y @instahost/cli share ./report.pdf --json
|
|
35
|
+
npx -y @instahost/cli share ./data.json --access private --ttl 1h --json
|
|
36
|
+
npx -y @instahost/cli publish ./dist --ttl 7d --json
|
|
37
|
+
npx -y @instahost/cli delete <id or URL> --token <delete_token> --json
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
A site is a directory with `index.html` at its root. Its pages must use relative URLs (for Vite, set `base: "./"`).
|
|
41
|
+
|
|
42
|
+
## Options
|
|
43
|
+
|
|
44
|
+
| Option | Commands | Meaning |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| `--json` | all | Print exactly one JSON document on stdout for every outcome, and nothing on stderr unless `--verbose`. |
|
|
47
|
+
| `--api-key <key>` | all | An API key (`ihk_...`); else `INSTAHOST_API_KEY`. Longer lifetimes, `--ttl never` and higher limits. Keys are issued by the operator. |
|
|
48
|
+
| `--verbose` | all | Diagnostics on stderr, with tokens and URL signatures masked. |
|
|
49
|
+
| `--help`, `-h` | all | Usage. With `--json`: `{"ok": true, "help": "..."}`. |
|
|
50
|
+
| `--version` | all | The CLI version. With `--json`: `{"ok": true, "version": "..."}`. |
|
|
51
|
+
| `--ttl <lifetime>` | share, publish | A number with `s`, `m`, `h` or `d` (`30m`, `24h`, `7d`), plain seconds, or `never` (persistent; needs an API key). Default 24 hours; anonymous maximum 7 days. |
|
|
52
|
+
| `--access <mode>` | share, publish | `unlisted` (default), `public`, or `private` (share only). |
|
|
53
|
+
| `--name <filename>` | share | The name to share the file under (no `/`); the default is the file's own name. |
|
|
54
|
+
| `--content-type <type>` | share | Declare the media type instead of deriving it from the extension. |
|
|
55
|
+
| `--include-dotfiles` | publish | Also publish dot-prefixed files and directories. Credentials, VCS data and OS metadata stay excluded. |
|
|
56
|
+
| `--concurrency <n>` | publish | Parallel uploads, 1 to 16 (default 6). |
|
|
57
|
+
| `--token <ihd_...>` | delete | The artifact's delete token. |
|
|
58
|
+
|
|
59
|
+
An option given to a command it does not belong to is a usage error. `delete` takes an artifact id or any of its URLs. Its credential is the first of `--token`, `--api-key`, `INSTAHOST_DELETE_TOKEN` and `INSTAHOST_API_KEY`; the environment keeps the token out of the process list.
|
|
60
|
+
|
|
61
|
+
## Access and lifetimes
|
|
62
|
+
|
|
63
|
+
| Access | Who can open it |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `unlisted` (default) | Anyone with the URL. Sent with `X-Robots-Tag: noindex, nofollow`. |
|
|
66
|
+
| `public` | Anyone with the URL; it may be indexed. |
|
|
67
|
+
| `private` | Files only: only with the access token, through `access_url`. |
|
|
68
|
+
|
|
69
|
+
`expires_at` is fixed at create and counted from creation. Expiry and deletion take effect on the next request. Current limits are at [instahost.dev/v1/limits](https://instahost.dev/v1/limits).
|
|
70
|
+
|
|
71
|
+
## What share and publish refuse or skip
|
|
72
|
+
|
|
73
|
+
- `share` refuses symbolic links, directories, names that look like credentials, and any file whose real path goes through a credential or VCS directory (`.ssh`, `.git`, `.aws`, ...).
|
|
74
|
+
- `publish` refuses a directory inside such a directory, and one without a root `index.html`. It never follows symbolic links, and it skips credential and VCS names, OS metadata (`.DS_Store`, `Thumbs.db`, `desktop.ini`, `._*`, `__MACOSX/`) and dot-prefixed paths except `.well-known` (unless `--include-dotfiles`). Each skipped path is listed under `skipped` with its reason.
|
|
75
|
+
- Both refuse a file that changes between hashing and upload.
|
|
76
|
+
|
|
77
|
+
Detection is by name only: the CLI does not read file contents to find secrets. Publish a build output directory (`dist/`, `build/`, `out/`), never a repository root or home directory.
|
|
78
|
+
|
|
79
|
+
## Output
|
|
80
|
+
|
|
81
|
+
Without `--json`, the result goes to stdout (URL, access URL, expiry and the delete command, `npx -y @instahost/cli delete <id> --token ...`), and skipped files, warnings and errors go to stderr. With `--json`, `share` and `publish` print:
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{"ok": true, "id": "...", "type": "site", "access": "unlisted", "url": "https://<id>.instahost.cloud/",
|
|
85
|
+
"expires_at": "2026-11-29T10:00:00Z", "delete_token": "ihd_...", "access_token": null, "access_url": null,
|
|
86
|
+
"file_count": 12, "total_bytes": 482113,
|
|
87
|
+
"skipped": [{"path": ".git/", "reason": "sensitive"}],
|
|
88
|
+
"warnings": []}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`access_token` and `access_url` are set for private files. `delete` prints `{"ok": true, "id": "...", "status": "deleted", "deleted_at": "..."}`. Every failure prints one document:
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
{"ok": false, "error": {"code": "quota_exceeded", "message": "...", "details": {"scope": "client", "resets_at": "..."}, "exit_code": 6}}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
When a failure happens after the artifact was created, `error.details.artifact` holds `{id, url, delete_token, access_url}`, because the artifact may exist and its delete token is the only way to remove it.
|
|
98
|
+
|
|
99
|
+
## Exit codes
|
|
100
|
+
|
|
101
|
+
| Exit | Meaning |
|
|
102
|
+
|---|---|
|
|
103
|
+
| 0 | Success. |
|
|
104
|
+
| 1 | Internal error in the CLI (`internal_error`, `cli_load_failed`). |
|
|
105
|
+
| 2 | Usage: unknown command or option, bad value, missing credential, unsupported Node.js version. |
|
|
106
|
+
| 3 | Local input refused: missing file, not a file or directory, symbolic link, credential-like name, invalid or duplicate path, no `index.html`, empty directory, or over 10,000 files, all before any request; or a file that changed or became unreadable during the upload, after create (with `error.details.artifact`). |
|
|
107
|
+
| 4 | Authentication or authorization: HTTP 401 or 403. |
|
|
108
|
+
| 5 | Rejected by the server: 400, 413, 415, 422 and other 4xx not listed here. |
|
|
109
|
+
| 6 | Rate limited or over quota: HTTP 429. `error.details.retry_after_seconds` carries `Retry-After`. |
|
|
110
|
+
| 7 | Network or server failure: 5xx, connection errors, storage refusing an upload after retries, a malformed answer, or an unsafe URL from the server. |
|
|
111
|
+
| 8 | Publication failed during the uploads or `complete`: 409, 410 or 422. |
|
|
112
|
+
| 9 | Not found: HTTP 404. |
|
|
113
|
+
|
|
114
|
+
## Retries and safety
|
|
115
|
+
|
|
116
|
+
- 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.
|
|
117
|
+
- The `/uploads` and `complete` calls and `delete` are retried on network errors, 502, 503 and 504, and on 429 `rate_limited` after `Retry-After` (up to 60 s). A 429 `quota_exceeded` is reported at once. Create is never retried, so a quota is never charged twice.
|
|
118
|
+
- 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.
|
|
119
|
+
|
|
120
|
+
## Programmatic use
|
|
121
|
+
|
|
122
|
+
The package's JavaScript exports exist for InstaHost's own tests. They are not a supported SDK and may change in any release. Run the `instahost` bin instead.
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
MIT. Source: [github.com/instahost-dev/instahost](https://github.com/instahost-dev/instahost).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// InstaHost CLI entry point. Plain JavaScript on purpose: the Node version is checked before the
|
|
3
|
+
// compiled CLI (dist/) is imported, so an old Node gets one clear answer instead of a syntax error.
|
|
4
|
+
// The npm package named "instahost" (unscoped) is unrelated to this project; this is @instahost/cli.
|
|
5
|
+
import { nodeTooOld, tooOldDocument } from "../src/node-check.mjs";
|
|
6
|
+
|
|
7
|
+
const argv = process.argv.slice(2);
|
|
8
|
+
const json = argv.includes("--json");
|
|
9
|
+
if (nodeTooOld(process.versions.node)) {
|
|
10
|
+
const doc = tooOldDocument(process.versions.node);
|
|
11
|
+
if (json) process.stdout.write(`${JSON.stringify(doc)}\n`);
|
|
12
|
+
else process.stderr.write(`instahost: ${doc.error.message}\n`);
|
|
13
|
+
process.exit(2);
|
|
14
|
+
}
|
|
15
|
+
let main;
|
|
16
|
+
try {
|
|
17
|
+
({ main } = await import(new URL("../dist/main.js", import.meta.url).href));
|
|
18
|
+
} catch (err) {
|
|
19
|
+
// A damaged or partial install (dist/ missing or unreadable): still exactly one answer.
|
|
20
|
+
const code = (err && typeof err === "object" && "code" in err && typeof err.code === "string") ? err.code : "unknown";
|
|
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
|
+
if (json) process.stdout.write(`${JSON.stringify({ ok: false, error: { code: "cli_load_failed", message, details: { reason: code }, exit_code: 1 } })}\n`);
|
|
23
|
+
else process.stderr.write(`instahost: ${message}\n`);
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
process.exitCode = await main(argv);
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// The API client.
|
|
2
|
+
// - Every request sends the CLI User-Agent (workers.dev rejects some default library agents).
|
|
3
|
+
// - Authorization is only ever sent to the API origin; URLs the API returns for later calls
|
|
4
|
+
// (uploads_url, complete_url) must be on that origin too.
|
|
5
|
+
// - API calls time out after 30 s. Idempotent calls (uploads, complete, delete) are retried 3
|
|
6
|
+
// times on network errors and 502/503/504 (1 s, 2 s, 4 s apart) and on 429 after Retry-After.
|
|
7
|
+
// Create is never retried automatically.
|
|
8
|
+
import { USER_AGENT } from "./config.js";
|
|
9
|
+
import { CliError, EXIT, exitCodeForApiError } from "./errors.js";
|
|
10
|
+
import { describeUrl, redact } from "./redact.js";
|
|
11
|
+
export const API_TIMEOUT_MS = 30_000;
|
|
12
|
+
export const RETRIES = 3;
|
|
13
|
+
export const BACKOFF_SECONDS = [1, 2, 4];
|
|
14
|
+
/** A Retry-After longer than this is not waited for; the 429 is reported instead. */
|
|
15
|
+
export const MAX_RETRY_AFTER_SECONDS = 60;
|
|
16
|
+
const RETRYABLE_STATUS = new Set([502, 503, 504]);
|
|
17
|
+
export const realSleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
18
|
+
const IMF_FIXDATE = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/;
|
|
19
|
+
/** Retry-After in seconds (delta-seconds or an IMF-fixdate, RFC 9110), or null for anything else. */
|
|
20
|
+
export function retryAfterSeconds(header, now = Date.now()) {
|
|
21
|
+
if (header === null)
|
|
22
|
+
return null;
|
|
23
|
+
const value = header.trim();
|
|
24
|
+
if (/^\d{1,9}$/.test(value))
|
|
25
|
+
return Number(value);
|
|
26
|
+
if (!IMF_FIXDATE.test(value))
|
|
27
|
+
return null;
|
|
28
|
+
return Math.max(0, Math.ceil((Date.parse(value) - now) / 1000));
|
|
29
|
+
}
|
|
30
|
+
/** A short reason for a failed request or body read: "timeout" or the socket error code. */
|
|
31
|
+
function failureReason(err) {
|
|
32
|
+
if (!(err instanceof Error))
|
|
33
|
+
return "unknown";
|
|
34
|
+
if (err.name === "TimeoutError")
|
|
35
|
+
return "timeout";
|
|
36
|
+
return err.cause?.code ?? err.name;
|
|
37
|
+
}
|
|
38
|
+
export class ApiClient {
|
|
39
|
+
apiUrl;
|
|
40
|
+
#log;
|
|
41
|
+
#sleep;
|
|
42
|
+
#fetch;
|
|
43
|
+
constructor(options) {
|
|
44
|
+
this.apiUrl = options.apiUrl;
|
|
45
|
+
this.#log = options.log ?? (() => { });
|
|
46
|
+
this.#sleep = options.sleep ?? realSleep;
|
|
47
|
+
this.#fetch = options.fetch ?? fetch;
|
|
48
|
+
}
|
|
49
|
+
log(line) {
|
|
50
|
+
this.#log(redact(line));
|
|
51
|
+
}
|
|
52
|
+
sleep(seconds) {
|
|
53
|
+
return this.#sleep(seconds);
|
|
54
|
+
}
|
|
55
|
+
/** Resolves a path or an absolute URL the API returned; refuses any other origin. */
|
|
56
|
+
resolve(pathOrUrl) {
|
|
57
|
+
const url = new URL(pathOrUrl, this.apiUrl);
|
|
58
|
+
if (url.origin !== this.apiUrl) {
|
|
59
|
+
throw new CliError("unsafe_url", "The API returned a URL on another origin; refusing to send credentials there.", EXIT.network, { url: describeUrl(url.href) });
|
|
60
|
+
}
|
|
61
|
+
return url;
|
|
62
|
+
}
|
|
63
|
+
async call(method, pathOrUrl, options) {
|
|
64
|
+
const url = this.resolve(pathOrUrl);
|
|
65
|
+
const headers = { "user-agent": USER_AGENT, accept: "application/json" };
|
|
66
|
+
if (options.body !== undefined)
|
|
67
|
+
headers["content-type"] = "application/json";
|
|
68
|
+
if (options.token)
|
|
69
|
+
headers.authorization = `Bearer ${options.token}`;
|
|
70
|
+
const body = options.body === undefined ? undefined : JSON.stringify(options.body);
|
|
71
|
+
const attempts = options.idempotent ? RETRIES + 1 : 1;
|
|
72
|
+
for (let attempt = 1;; attempt++) {
|
|
73
|
+
const started = Date.now();
|
|
74
|
+
let res;
|
|
75
|
+
let text;
|
|
76
|
+
try {
|
|
77
|
+
// The body read is guarded too: a connection cut or the timeout during the body is a
|
|
78
|
+
// network failure like any other (retried when the call is idempotent).
|
|
79
|
+
res = await this.#fetch(url, { method, headers, body, redirect: "error", signal: AbortSignal.timeout(API_TIMEOUT_MS) });
|
|
80
|
+
text = await res.text();
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
const reason = failureReason(err);
|
|
84
|
+
this.log(`api ${method} ${url.pathname} failed (${reason})`);
|
|
85
|
+
if (attempt < attempts) {
|
|
86
|
+
await this.#sleep(BACKOFF_SECONDS[attempt - 1] ?? 4);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
throw new CliError("network_error", `Could not reach the API at ${this.apiUrl}.`, EXIT.network, { reason });
|
|
90
|
+
}
|
|
91
|
+
this.log(`api ${method} ${url.pathname} -> ${res.status} (${Date.now() - started} ms)`);
|
|
92
|
+
let parsed = null;
|
|
93
|
+
try {
|
|
94
|
+
parsed = text ? JSON.parse(text) : null;
|
|
95
|
+
}
|
|
96
|
+
catch { }
|
|
97
|
+
if (res.ok) {
|
|
98
|
+
if (parsed === null || typeof parsed !== "object")
|
|
99
|
+
throw new CliError("bad_response", `The API answered ${res.status} without a JSON body.`, EXIT.network, undefined, res.status);
|
|
100
|
+
return parsed;
|
|
101
|
+
}
|
|
102
|
+
const envelope = parsed?.error;
|
|
103
|
+
const code = typeof envelope?.code === "string" ? envelope.code : `http_${res.status}`;
|
|
104
|
+
if (attempt < attempts) {
|
|
105
|
+
if (RETRYABLE_STATUS.has(res.status)) {
|
|
106
|
+
await this.#sleep(BACKOFF_SECONDS[attempt - 1] ?? 4);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (res.status === 429 && code === "rate_limited") {
|
|
110
|
+
const wait = retryAfterSeconds(res.headers.get("retry-after")) ?? BACKOFF_SECONDS[attempt - 1] ?? 4;
|
|
111
|
+
if (wait <= MAX_RETRY_AFTER_SECONDS) {
|
|
112
|
+
this.log(`api rate limited; retrying in ${wait} s`);
|
|
113
|
+
await this.#sleep(wait);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const message = typeof envelope?.message === "string" ? envelope.message : `The API answered ${res.status}.`;
|
|
119
|
+
const details = envelope?.details && typeof envelope.details === "object" ? envelope.details : undefined;
|
|
120
|
+
const retryAfter = retryAfterSeconds(res.headers.get("retry-after"));
|
|
121
|
+
throw new CliError(code, redact(message), exitCodeForApiError(res.status, code, options.phase), retryAfter === null ? details : { ...details, retry_after_seconds: retryAfter }, res.status);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// instahost delete <id|url>. The credential is the artifact's delete
|
|
2
|
+
// token (--token or INSTAHOST_DELETE_TOKEN) or the owner's API key. DELETE is idempotent on the
|
|
3
|
+
// server, so it is retried like the other idempotent calls.
|
|
4
|
+
import { CliError, EXIT, usageError } from "../errors.js";
|
|
5
|
+
const ARTIFACT_ID = /^[a-z2-7]{26}$/;
|
|
6
|
+
/**
|
|
7
|
+
* The artifact id from an id or from one of its URLs. A subdomain-mode site URL carries the id as
|
|
8
|
+
* its first host label, and that wins: the site's own paths may contain id-shaped segments
|
|
9
|
+
* (https://<A>.<content>/<B>/ is a page of site A, not artifact B). Otherwise the id is the first
|
|
10
|
+
* path segment (files URLs, path-mode site URLs).
|
|
11
|
+
*/
|
|
12
|
+
export function parseArtifactRef(ref) {
|
|
13
|
+
const trimmed = ref.trim();
|
|
14
|
+
if (ARTIFACT_ID.test(trimmed))
|
|
15
|
+
return trimmed;
|
|
16
|
+
try {
|
|
17
|
+
const url = new URL(trimmed);
|
|
18
|
+
const label = url.hostname.split(".")[0] ?? "";
|
|
19
|
+
if (ARTIFACT_ID.test(label))
|
|
20
|
+
return label;
|
|
21
|
+
const segment = url.pathname.split("/")[1] ?? "";
|
|
22
|
+
if (ARTIFACT_ID.test(segment))
|
|
23
|
+
return segment;
|
|
24
|
+
}
|
|
25
|
+
catch { }
|
|
26
|
+
throw usageError(`${JSON.stringify(ref)} is not an artifact id (26 characters a-z and 2-7) or an artifact URL.`);
|
|
27
|
+
}
|
|
28
|
+
export async function deleteArtifact(ctx, options) {
|
|
29
|
+
const id = parseArtifactRef(options.ref);
|
|
30
|
+
const credential = options.credential;
|
|
31
|
+
if (!credential)
|
|
32
|
+
throw usageError("delete needs the artifact's delete token (--token or INSTAHOST_DELETE_TOKEN) or the owner's API key.");
|
|
33
|
+
const r = await ctx.client.call("DELETE", `/v1/artifacts/${id}`, {
|
|
34
|
+
token: credential,
|
|
35
|
+
idempotent: true,
|
|
36
|
+
phase: "delete",
|
|
37
|
+
});
|
|
38
|
+
if (typeof r?.artifact?.id !== "string" || typeof r.artifact.status !== "string")
|
|
39
|
+
throw new CliError("bad_response", "The API's answer to delete has no artifact.", EXIT.network);
|
|
40
|
+
return { ok: true, id: r.artifact.id, status: r.artifact.status, deleted_at: r.artifact.deleted_at ?? null };
|
|
41
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// instahost publish <dir>. Like share,
|
|
2
|
+
// it refuses a directory whose real path crosses a sensitive directory (publishing ~/.ssh or a .git
|
|
3
|
+
// folder whole); the walk then applies the exclusions to the paths inside it.
|
|
4
|
+
import { realpath, stat } from "node:fs/promises";
|
|
5
|
+
import { sep } from "node:path";
|
|
6
|
+
import { inputError } from "../errors.js";
|
|
7
|
+
import { sensitiveRule } from "../vendor/paths.js";
|
|
8
|
+
import { lifetimeFields } from "../ttl.js";
|
|
9
|
+
import { afterCreate, checkCreated, uploadAndComplete } from "../upload.js";
|
|
10
|
+
import { findRootAbsoluteReferences, walkSite } from "../walk.js";
|
|
11
|
+
const MAX_WARNING_PATHS = 20;
|
|
12
|
+
export async function publish(ctx, options) {
|
|
13
|
+
const display = options.dir;
|
|
14
|
+
try {
|
|
15
|
+
if (!(await stat(options.dir)).isDirectory())
|
|
16
|
+
throw inputError("not_a_directory", `${display} is not a directory; use instahost share for a single file.`, { path: display });
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
if (err.name === "CliError")
|
|
20
|
+
throw err;
|
|
21
|
+
throw inputError("file_not_found", `${display} does not exist.`, { path: display });
|
|
22
|
+
}
|
|
23
|
+
const rule = sensitiveRule(`${(await realpath(options.dir)).split(sep).filter(Boolean).join("/")}/index.html`);
|
|
24
|
+
if (rule)
|
|
25
|
+
throw inputError("sensitive_file", `Refusing to publish ${display}: it is inside a credential or VCS directory (${rule}).`, { paths: [{ path: display, reason: rule }] });
|
|
26
|
+
const walked = await walkSite(options.dir, { includeDotfiles: options.includeDotfiles });
|
|
27
|
+
if (walked.files.length === 0) {
|
|
28
|
+
throw inputError("empty_directory", `${display} has no files to publish.`, { path: display, skipped: walked.skipped.length });
|
|
29
|
+
}
|
|
30
|
+
if (!walked.files.some((f) => f.path === "index.html")) {
|
|
31
|
+
throw inputError("missing_index", `${display} has no index.html at its root; a site needs one.`, { path: display });
|
|
32
|
+
}
|
|
33
|
+
const rootAbsolute = await findRootAbsoluteReferences(walked.files);
|
|
34
|
+
const created = await ctx.client.call("POST", "/v1/artifacts", {
|
|
35
|
+
body: { type: "site", access: options.access, ...lifetimeFields(options.lifetime), files: walked.files.map((f) => ({ path: f.path, size: f.size, md5: f.md5 })) },
|
|
36
|
+
token: ctx.apiKey,
|
|
37
|
+
idempotent: false,
|
|
38
|
+
phase: "create",
|
|
39
|
+
});
|
|
40
|
+
checkCreated(created);
|
|
41
|
+
const artifact = await afterCreate(created, () => uploadAndComplete({
|
|
42
|
+
client: ctx.client,
|
|
43
|
+
created,
|
|
44
|
+
apiKey: ctx.apiKey,
|
|
45
|
+
files: walked.files,
|
|
46
|
+
concurrency: options.concurrency,
|
|
47
|
+
onProgress: ctx.onProgress,
|
|
48
|
+
fetch: ctx.fetch,
|
|
49
|
+
}));
|
|
50
|
+
// Root-absolute references only break when the site lives under a path (path mode).
|
|
51
|
+
const warnings = [];
|
|
52
|
+
if (rootAbsolute.length && new URL(artifact.url).pathname !== "/") {
|
|
53
|
+
const paths = rootAbsolute.map((r) => r.path);
|
|
54
|
+
warnings.push({
|
|
55
|
+
code: "root_absolute_reference",
|
|
56
|
+
message: `${paths.length} file(s) use root-absolute URLs ("/app.js")${rootAbsolute.some((r) => r.base) ? " or <base href=\"/\">" : ""}, which break under ${new URL(artifact.url).pathname}; use relative URLs (for example Vite base: "./")`,
|
|
57
|
+
paths: paths.slice(0, MAX_WARNING_PATHS),
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
ok: true,
|
|
62
|
+
id: artifact.id,
|
|
63
|
+
type: "site",
|
|
64
|
+
access: artifact.access,
|
|
65
|
+
url: artifact.url,
|
|
66
|
+
expires_at: artifact.expires_at,
|
|
67
|
+
delete_token: created.delete_token,
|
|
68
|
+
access_token: null,
|
|
69
|
+
access_url: null,
|
|
70
|
+
file_count: artifact.file_count,
|
|
71
|
+
total_bytes: artifact.total_bytes,
|
|
72
|
+
skipped: walked.skipped,
|
|
73
|
+
warnings,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// instahost share <file>.
|
|
2
|
+
// Refuses symlinks, and refuses names that look like credentials: the shared name (--name or the
|
|
3
|
+
// file's own name), the real file's name, and every directory on its real path (so a file inside
|
|
4
|
+
// ~/.ssh or .git is refused even if its own name looks harmless).
|
|
5
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
6
|
+
import { basename, resolve, sep } from "node:path";
|
|
7
|
+
import { CliError, EXIT, inputError } from "../errors.js";
|
|
8
|
+
import { lifetimeFields } from "../ttl.js";
|
|
9
|
+
import { afterCreate, checkCreated, uploadAndComplete } from "../upload.js";
|
|
10
|
+
import { sensitiveRule, validatePath } from "../vendor/paths.js";
|
|
11
|
+
import { hashFile } from "../walk.js";
|
|
12
|
+
function refuseSensitive(label, path) {
|
|
13
|
+
const rule = sensitiveRule(path);
|
|
14
|
+
if (rule)
|
|
15
|
+
throw inputError("sensitive_file", `Refusing to share ${label}: it looks like a credential or VCS data (${rule}).`, { paths: [{ path: basename(path), reason: rule }] });
|
|
16
|
+
}
|
|
17
|
+
export async function share(ctx, options) {
|
|
18
|
+
const display = options.file;
|
|
19
|
+
let info;
|
|
20
|
+
try {
|
|
21
|
+
info = await lstat(options.file);
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
const code = err.code;
|
|
25
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
26
|
+
throw inputError("file_not_found", `${display} does not exist.`, { path: display });
|
|
27
|
+
throw inputError("unreadable_file", `${display} cannot be read (${code ?? "error"}).`, { path: display });
|
|
28
|
+
}
|
|
29
|
+
if (info.isSymbolicLink())
|
|
30
|
+
throw inputError("symlink_refused", `${display} is a symbolic link; share the file it points to instead.`, { path: display });
|
|
31
|
+
if (info.isDirectory())
|
|
32
|
+
throw inputError("not_a_file", `${display} is a directory; use instahost publish for directories.`, { path: display });
|
|
33
|
+
if (!info.isFile())
|
|
34
|
+
throw inputError("not_a_file", `${display} is not a regular file.`, { path: display });
|
|
35
|
+
const real = await realpath(options.file);
|
|
36
|
+
const name = (options.name ?? basename(resolve(options.file))).normalize("NFC");
|
|
37
|
+
const check = validatePath(name);
|
|
38
|
+
if (!check.ok || name.includes("/")) {
|
|
39
|
+
throw inputError("invalid_path", `The file name ${JSON.stringify(name)} cannot be used${check.ok ? " (no / allowed)" : ` (${check.reason})`}; pass --name.`, {
|
|
40
|
+
paths: [{ path: name, reason: check.ok ? "slash" : check.reason }],
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
refuseSensitive(JSON.stringify(name), name);
|
|
44
|
+
refuseSensitive(display, basename(real));
|
|
45
|
+
refuseSensitive(display, real.split(sep).filter(Boolean).join("/"));
|
|
46
|
+
const { size, md5, dev, ino } = await hashFile(options.file, display);
|
|
47
|
+
const file = { path: name, size, md5 };
|
|
48
|
+
if (options.contentType !== undefined)
|
|
49
|
+
file.content_type = options.contentType;
|
|
50
|
+
const created = await ctx.client.call("POST", "/v1/artifacts", {
|
|
51
|
+
body: { type: "file", access: options.access, ...lifetimeFields(options.lifetime), files: [file] },
|
|
52
|
+
token: ctx.apiKey,
|
|
53
|
+
idempotent: false,
|
|
54
|
+
phase: "create",
|
|
55
|
+
});
|
|
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
|
+
return {
|
|
69
|
+
ok: true,
|
|
70
|
+
id: artifact.id,
|
|
71
|
+
type: "file",
|
|
72
|
+
access: artifact.access,
|
|
73
|
+
url: artifact.url,
|
|
74
|
+
expires_at: artifact.expires_at,
|
|
75
|
+
delete_token: created.delete_token,
|
|
76
|
+
access_token: created.access_token ?? null,
|
|
77
|
+
access_url: created.access_url ?? null,
|
|
78
|
+
file_count: artifact.file_count,
|
|
79
|
+
total_bytes: artifact.total_bytes,
|
|
80
|
+
skipped: [],
|
|
81
|
+
warnings: [],
|
|
82
|
+
};
|
|
83
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// CLI configuration.
|
|
2
|
+
// Precedence: flag, then environment, then DEFAULT_API_URL, the production API origin. Empty
|
|
3
|
+
// means the CLI asks for an API URL.
|
|
4
|
+
import { usageError } from "./errors.js";
|
|
5
|
+
export const VERSION = "0.1.0";
|
|
6
|
+
/**
|
|
7
|
+
* The production API origin. The service's deploy preflight refuses to deploy an API origin that
|
|
8
|
+
* differs from this value in the CLI version it pins, so changing the API domain needs a CLI release
|
|
9
|
+
* first. Keep it on one line.
|
|
10
|
+
*/
|
|
11
|
+
export const DEFAULT_API_URL = "https://instahost.dev";
|
|
12
|
+
export const USER_AGENT = `instahost-cli/${VERSION} (node/${process.versions.node})`;
|
|
13
|
+
/**
|
|
14
|
+
* Loopback hosts: the only ones http:// is accepted for. `localhost` itself, IPv4
|
|
15
|
+
* 127.0.0.0/8 and [::1]. Other `*.localhost` names are refused: Node resolves them through the
|
|
16
|
+
* system resolver, which may ask DNS before mapping them to loopback.
|
|
17
|
+
*/
|
|
18
|
+
export function isLoopbackHost(hostname) {
|
|
19
|
+
const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
20
|
+
return h === "localhost" || /^127(?:\.\d{1,3}){3}$/.test(h) || h === "::1";
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Parses and checks an API base URL: https, or http on a loopback host; no credentials, query or
|
|
24
|
+
* fragment; an optional trailing slash. Returns the origin (the API serves /v1 at its root).
|
|
25
|
+
*/
|
|
26
|
+
export function parseApiUrl(raw) {
|
|
27
|
+
let url;
|
|
28
|
+
try {
|
|
29
|
+
url = new URL(raw.trim());
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
throw usageError(`The API URL is not a valid URL: ${JSON.stringify(raw)}.`);
|
|
33
|
+
}
|
|
34
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopbackHost(url.hostname))) {
|
|
35
|
+
throw usageError("The API URL must use https:// (http:// is accepted only for localhost).", { api_url: url.origin });
|
|
36
|
+
}
|
|
37
|
+
if (url.username || url.password || url.search || url.hash)
|
|
38
|
+
throw usageError("The API URL must not contain credentials, a query or a fragment.");
|
|
39
|
+
if (url.pathname !== "/" && url.pathname !== "")
|
|
40
|
+
throw usageError("The API URL is the service origin, for example https://instahost.dev (no path).", { api_url: url.origin });
|
|
41
|
+
return url.origin;
|
|
42
|
+
}
|
|
43
|
+
export function resolveApiUrl(flag, env, defaultUrl = DEFAULT_API_URL) {
|
|
44
|
+
const raw = flag ?? (env.INSTAHOST_API_URL || undefined) ?? (defaultUrl || undefined);
|
|
45
|
+
if (!raw)
|
|
46
|
+
throw usageError("No API URL: pass --api-url <url> or set INSTAHOST_API_URL.");
|
|
47
|
+
return parseApiUrl(raw);
|
|
48
|
+
}
|
|
49
|
+
const API_KEY = /^ihk_[a-z2-7]{12}_[A-Za-z0-9_-]{43}$/;
|
|
50
|
+
const DELETE_TOKEN = /^ihd_[A-Za-z0-9_-]{43}$/;
|
|
51
|
+
export function resolveApiKey(flag, env) {
|
|
52
|
+
const raw = flag ?? (env.INSTAHOST_API_KEY || undefined);
|
|
53
|
+
if (raw === undefined)
|
|
54
|
+
return null;
|
|
55
|
+
if (!API_KEY.test(raw))
|
|
56
|
+
throw usageError("The API key is malformed (expected ihk_<id>_<secret>).");
|
|
57
|
+
return raw;
|
|
58
|
+
}
|
|
59
|
+
export function resolveDeleteToken(flag, env) {
|
|
60
|
+
const raw = flag ?? (env.INSTAHOST_DELETE_TOKEN || undefined);
|
|
61
|
+
if (raw === undefined)
|
|
62
|
+
return null;
|
|
63
|
+
if (!DELETE_TOKEN.test(raw))
|
|
64
|
+
throw usageError("The delete token is malformed (expected ihd_<43 characters>).");
|
|
65
|
+
return raw;
|
|
66
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// CLI errors and exit codes.
|
|
2
|
+
// Every failure becomes a CliError with a stable code, so --json can always print one document.
|
|
3
|
+
export const EXIT = {
|
|
4
|
+
ok: 0,
|
|
5
|
+
internal: 1,
|
|
6
|
+
usage: 2,
|
|
7
|
+
localInput: 3,
|
|
8
|
+
auth: 4,
|
|
9
|
+
rejected: 5,
|
|
10
|
+
rateLimited: 6,
|
|
11
|
+
network: 7,
|
|
12
|
+
publishFailed: 8,
|
|
13
|
+
notFound: 9,
|
|
14
|
+
};
|
|
15
|
+
export class CliError extends Error {
|
|
16
|
+
name = "CliError";
|
|
17
|
+
code;
|
|
18
|
+
exitCode;
|
|
19
|
+
details;
|
|
20
|
+
/** HTTP status of the API answer behind this error, if any. */
|
|
21
|
+
status;
|
|
22
|
+
/** Set when the failure came after create: the artifact may exist (it may even be published). */
|
|
23
|
+
artifact;
|
|
24
|
+
constructor(code, message, exitCode, details, status) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.exitCode = exitCode;
|
|
28
|
+
this.details = details;
|
|
29
|
+
this.status = status;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export const usageError = (message, details) => new CliError("usage", message, EXIT.usage, details);
|
|
33
|
+
export const inputError = (code, message, details) => new CliError(code, message, EXIT.localInput, details);
|
|
34
|
+
/** API error codes that end a publication (exit 8) wherever they appear in the publish phase. */
|
|
35
|
+
const PUBLICATION_CODES = new Set(["upload_mismatch", "upload_incomplete", "artifact_failed", "artifact_not_pending", "upload_url_limit", "complete_attempt_limit", "gone"]);
|
|
36
|
+
/**
|
|
37
|
+
* Exit code for an error envelope from the API. Order matters: 429 and 401/403 win over the phase,
|
|
38
|
+
* 404 is not found, 5xx is a server failure.
|
|
39
|
+
*/
|
|
40
|
+
export function exitCodeForApiError(status, code, phase) {
|
|
41
|
+
if (status === 429)
|
|
42
|
+
return EXIT.rateLimited;
|
|
43
|
+
if (status === 401 || status === 403)
|
|
44
|
+
return EXIT.auth;
|
|
45
|
+
if (status === 404)
|
|
46
|
+
return EXIT.notFound;
|
|
47
|
+
if (status >= 500)
|
|
48
|
+
return EXIT.network;
|
|
49
|
+
if (phase === "publish" && (PUBLICATION_CODES.has(code) || status === 409 || status === 410 || status === 422))
|
|
50
|
+
return EXIT.publishFailed;
|
|
51
|
+
if (status >= 400)
|
|
52
|
+
return EXIT.rejected;
|
|
53
|
+
return EXIT.internal;
|
|
54
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The package's import surface, used by the InstaHost service's own tests and scripts. It is not
|
|
2
|
+
// a supported SDK: anything here may change in any release. Run the CLI through its bin instead.
|
|
3
|
+
export { main, HELP, OPTIONS } from "./main.js";
|
|
4
|
+
export { EXIT, exitCodeForApiError } from "./errors.js";
|
|
5
|
+
export { VERSION, DEFAULT_API_URL } from "./config.js";
|
|
6
|
+
export { redact } from "./redact.js";
|