filecafe 0.0.0-stage → 0.1.1
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 +128 -2
- package/dist/cli.js +1040 -0
- package/package.json +40 -4
package/README.md
CHANGED
|
@@ -1,3 +1,129 @@
|
|
|
1
|
-
#
|
|
1
|
+
# filecafe
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Upload files to [file.cafe](https://file.cafe) from the command line and get share links back.
|
|
4
|
+
|
|
5
|
+
Built for AI coding agents (Claude Code, Codex, Cursor), humans, and CI: share URLs go to stdout, progress and errors go to stderr, `--json` gives machine-readable results, and nothing ever prompts (except the one-time browser login).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Run it without installing:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npx filecafe upload report.pdf
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or install it globally:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm i -g filecafe
|
|
19
|
+
filecafe --help
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Requires Node.js 20 or newer.
|
|
23
|
+
|
|
24
|
+
## Log in
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
filecafe login
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
This opens your browser so you can approve the CLI on file.cafe. The token is saved to `~/.config/filecafe/config.json` (or `$XDG_CONFIG_HOME/filecafe/config.json`; `%APPDATA%\filecafe\config.json` on Windows) with owner-only permissions.
|
|
31
|
+
|
|
32
|
+
Headless machines and CI can use an existing token instead:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
echo "$FILECAFE_TOKEN" | filecafe login --with-token # validate and save
|
|
36
|
+
# ...or skip saving entirely and just set FILECAFE_TOKEN for each run
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Other account commands:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
filecafe whoami # Logged in to https://file.cafe as Ada (ada@example.com)
|
|
43
|
+
filecafe whoami --json # {"name":"Ada","email":"ada@example.com","url":"https://file.cafe","token_source":"config"}
|
|
44
|
+
filecafe logout # revoke the saved token on file.cafe and delete it locally
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Saved logins never expire. They last until you run `filecafe logout` or revoke the token in
|
|
48
|
+
Settings → API tokens on file.cafe. `logout` revokes the token even if you saved it with
|
|
49
|
+
`filecafe login --token`, so don't log out with a token that CI or another machine still uses.
|
|
50
|
+
|
|
51
|
+
## Upload
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
filecafe upload screenshot.png # prints the share URL
|
|
55
|
+
filecafe upload a.png b.mp4 notes.txt # one URL per line, in order
|
|
56
|
+
filecafe upload build.zip | pbcopy # copy the link to the clipboard
|
|
57
|
+
filecafe upload video.mp4 --collection <uuid> # add to a collection
|
|
58
|
+
filecafe upload report.pdf --json # machine-readable output
|
|
59
|
+
filecafe upload big.mov --quiet # no progress output
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Files are uploaded one after another; large files (over 64 MiB) are split into parts that upload in parallel. Every input is checked before anything is uploaded: if any path is missing or is not a regular file, nothing is uploaded.
|
|
63
|
+
|
|
64
|
+
### `--json` output
|
|
65
|
+
|
|
66
|
+
A single JSON array on stdout with one object per input file, in the order given:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
[
|
|
70
|
+
{
|
|
71
|
+
"file": "report.pdf",
|
|
72
|
+
"ok": true,
|
|
73
|
+
"id": "9d3c3f8e-5a8b-4c1e-9f0a-2b7d6e4c1a90",
|
|
74
|
+
"filename": "report.pdf",
|
|
75
|
+
"size": 482113,
|
|
76
|
+
"url": "https://file.cafe/...",
|
|
77
|
+
"password_protected": false
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
"file": "missing.png",
|
|
81
|
+
"ok": false,
|
|
82
|
+
"error": "No such file."
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The exit code is `0` if every file uploaded and `1` if any failed.
|
|
88
|
+
|
|
89
|
+
## Configuration
|
|
90
|
+
|
|
91
|
+
| Setting | How to set | Default |
|
|
92
|
+
| --- | --- | --- |
|
|
93
|
+
| Site URL | `--url <url>`, then `FILECAFE_URL`, then the URL you logged in to | `https://file.cafe` |
|
|
94
|
+
| API token | `FILECAFE_TOKEN`, then the token saved by `filecafe login` | none |
|
|
95
|
+
|
|
96
|
+
A saved token is only ever sent to the site it was issued for. To work against another server (for example a local development site), log in to it explicitly: `filecafe login --url http://file-cafe.test`.
|
|
97
|
+
|
|
98
|
+
Set `FILECAFE_DEBUG=1` to print stack traces for unexpected errors.
|
|
99
|
+
|
|
100
|
+
## Using file.cafe with AI agents
|
|
101
|
+
|
|
102
|
+
Paste this into your project's `CLAUDE.md`, `AGENTS.md`, or Cursor rules:
|
|
103
|
+
|
|
104
|
+
```markdown
|
|
105
|
+
## Sharing files
|
|
106
|
+
|
|
107
|
+
To share a file with the user (screenshots, build artifacts, logs, exports), run:
|
|
108
|
+
|
|
109
|
+
npx -y filecafe upload <path> --json
|
|
110
|
+
|
|
111
|
+
and give the user the `url` from the JSON output. Upload several files at once by passing
|
|
112
|
+
multiple paths. If the command fails with "Not logged in", ask the user to run
|
|
113
|
+
`npx filecafe login` (or set `FILECAFE_TOKEN`) and then try again.
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Agents can run `filecafe --help` and `filecafe upload --help` to see every option with examples.
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```sh
|
|
121
|
+
npm install
|
|
122
|
+
npm run typecheck
|
|
123
|
+
npm test # node:test, runs the TypeScript sources directly (Node 24)
|
|
124
|
+
npm run build # bundles to dist/cli.js with tsdown
|
|
125
|
+
node dist/cli.js --help
|
|
126
|
+
npm run dev -- --url http://file-cafe.test whoami # run from source
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Releases are published to npm from GitHub Actions when a `v*` tag is pushed (npm trusted publishing with provenance). Bump `version` in `package.json` to match the tag first.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1040 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import { homedir, hostname } from "node:os";
|
|
4
|
+
import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { basename, dirname, extname, join } from "node:path";
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
8
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { openAsBlob } from "node:fs";
|
|
11
|
+
// src/api.ts
|
|
12
|
+
const LOGIN_HINT = "Run \"filecafe login\" or set FILECAFE_TOKEN.";
|
|
13
|
+
var ApiError = class extends Error {
|
|
14
|
+
/** HTTP status, or null for network-level failures. */
|
|
15
|
+
status;
|
|
16
|
+
constructor(message, status) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = "ApiError";
|
|
19
|
+
this.status = status;
|
|
20
|
+
}
|
|
21
|
+
/** Errors that will fail every subsequent request too (bad token, unverified account). */
|
|
22
|
+
get isFatal() {
|
|
23
|
+
return this.status === 401 || this.status === 403;
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const MAX_RETRY_AFTER_SECONDS = 120;
|
|
27
|
+
/** Parse a Retry-After header (delta-seconds or HTTP date) into milliseconds. */
|
|
28
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
29
|
+
if (!value) return null;
|
|
30
|
+
const trimmed = value.trim();
|
|
31
|
+
if (/^\d+$/.test(trimmed)) return Math.min(Number(trimmed), MAX_RETRY_AFTER_SECONDS) * 1e3;
|
|
32
|
+
const date = Date.parse(trimmed);
|
|
33
|
+
if (Number.isNaN(date)) return null;
|
|
34
|
+
return Math.min(Math.max(date - now, 0), MAX_RETRY_AFTER_SECONDS * 1e3);
|
|
35
|
+
}
|
|
36
|
+
function messageFrom(body) {
|
|
37
|
+
if (body && typeof body === "object" && "message" in body && typeof body.message === "string" && body.message) return body.message;
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
/** Build the user-facing message for a failed API response. */
|
|
41
|
+
function apiErrorMessage(status, body) {
|
|
42
|
+
const message = messageFrom(body);
|
|
43
|
+
switch (status) {
|
|
44
|
+
case 401: return `Authentication failed: your token is missing, invalid, or revoked. ${LOGIN_HINT}`;
|
|
45
|
+
case 403: return message ?? "This action is not allowed for your account.";
|
|
46
|
+
case 404: return message && message !== "Not Found." ? message : "Not found. Check the --url option and the IDs you passed.";
|
|
47
|
+
case 422: {
|
|
48
|
+
const errors = body && typeof body === "object" && "errors" in body && body.errors && typeof body.errors === "object" ? body.errors : {};
|
|
49
|
+
const firstMessages = Object.values(errors).map((value) => Array.isArray(value) ? value[0] : value).filter((value) => typeof value === "string" && value.length > 0);
|
|
50
|
+
if (firstMessages.length > 0) return firstMessages.join(" ");
|
|
51
|
+
return message ?? "The request was invalid.";
|
|
52
|
+
}
|
|
53
|
+
case 429: return message ?? "Too many requests. Please wait a minute and try again.";
|
|
54
|
+
case 503: return message ?? "file.cafe is temporarily unavailable. Please try again later.";
|
|
55
|
+
default: return message ? `${message} (HTTP ${status})` : `Request failed with HTTP ${status}.`;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function describeNetworkError(error) {
|
|
59
|
+
if (error instanceof Error) {
|
|
60
|
+
if (error.name === "TimeoutError" || error.name === "AbortError") return "the request timed out";
|
|
61
|
+
const cause = error.cause;
|
|
62
|
+
if (cause && typeof cause === "object") {
|
|
63
|
+
const code = "code" in cause && typeof cause.code === "string" ? cause.code : null;
|
|
64
|
+
const causeMessage = "message" in cause && typeof cause.message === "string" ? cause.message : null;
|
|
65
|
+
return code ?? causeMessage ?? error.message;
|
|
66
|
+
}
|
|
67
|
+
return error.message;
|
|
68
|
+
}
|
|
69
|
+
return String(error);
|
|
70
|
+
}
|
|
71
|
+
function createApiClient(options) {
|
|
72
|
+
const { baseUrl, token, fetch, sleep, userAgent, onNotice, maxRateLimitRetries = 3, maxNetworkRetries = 3, timeoutMs = 6e4 } = options;
|
|
73
|
+
async function request(method, path, body, requestOptions = {}) {
|
|
74
|
+
const url = `${baseUrl}${path}`;
|
|
75
|
+
let rateLimitRetries = 0;
|
|
76
|
+
let networkRetries = 0;
|
|
77
|
+
for (;;) {
|
|
78
|
+
const headers = {
|
|
79
|
+
Accept: "application/json",
|
|
80
|
+
Authorization: `Bearer ${token}`,
|
|
81
|
+
"User-Agent": userAgent
|
|
82
|
+
};
|
|
83
|
+
if (body !== void 0) headers["Content-Type"] = "application/json";
|
|
84
|
+
let response;
|
|
85
|
+
let text;
|
|
86
|
+
try {
|
|
87
|
+
response = await fetch(url, {
|
|
88
|
+
method,
|
|
89
|
+
headers,
|
|
90
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
91
|
+
redirect: "manual",
|
|
92
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
93
|
+
});
|
|
94
|
+
text = await response.text();
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (requestOptions.idempotent && networkRetries < maxNetworkRetries) {
|
|
97
|
+
networkRetries++;
|
|
98
|
+
await sleep(1e3 * 2 ** (networkRetries - 1));
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
throw new ApiError(`Could not reach ${baseUrl} (${describeNetworkError(error)}).`, null);
|
|
102
|
+
}
|
|
103
|
+
if (response.status >= 300 && response.status < 400) throw new ApiError(`${url} redirected to ${response.headers.get("Location") ?? "another location"}. Check the --url option / FILECAFE_URL (e.g. use https:// instead of http://).`, response.status);
|
|
104
|
+
let json = null;
|
|
105
|
+
if (text) try {
|
|
106
|
+
json = JSON.parse(text);
|
|
107
|
+
} catch {
|
|
108
|
+
json = null;
|
|
109
|
+
}
|
|
110
|
+
if (response.status === 429 && rateLimitRetries < maxRateLimitRetries) {
|
|
111
|
+
rateLimitRetries++;
|
|
112
|
+
const waitMs = parseRetryAfter(response.headers.get("Retry-After")) ?? 5e3 * rateLimitRetries;
|
|
113
|
+
onNotice?.(`Rate limited by ${baseUrl}; retrying in ${Math.ceil(waitMs / 1e3)}s...`);
|
|
114
|
+
await sleep(waitMs);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (requestOptions.idempotent && (response.status === 502 || response.status === 504) && networkRetries < maxNetworkRetries) {
|
|
118
|
+
networkRetries++;
|
|
119
|
+
await sleep(1e3 * 2 ** (networkRetries - 1));
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (!response.ok) throw new ApiError(apiErrorMessage(response.status, json), response.status);
|
|
123
|
+
if (response.status === 204) return;
|
|
124
|
+
if (json && typeof json === "object" && "data" in json) return json.data;
|
|
125
|
+
throw new ApiError(`Unexpected response from ${url} (HTTP ${response.status}, not file.cafe API JSON). Check the --url option / FILECAFE_URL.`, response.status);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
baseUrl,
|
|
130
|
+
request
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
async function fetchMe(client) {
|
|
134
|
+
const me = await client.request("GET", "/api/v1/me", void 0, { idempotent: true });
|
|
135
|
+
if (!me || typeof me.email !== "string") throw new ApiError("Unexpected response from /api/v1/me.", null);
|
|
136
|
+
return {
|
|
137
|
+
name: typeof me.name === "string" ? me.name : "",
|
|
138
|
+
email: me.email
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Location of the config file:
|
|
143
|
+
* - Windows: %APPDATA%\filecafe\config.json
|
|
144
|
+
* - Elsewhere: $XDG_CONFIG_HOME/filecafe/config.json, falling back to ~/.config/filecafe/config.json
|
|
145
|
+
*/
|
|
146
|
+
function configPath({ env, platform, homedir }) {
|
|
147
|
+
if (platform === "win32") {
|
|
148
|
+
const appData = env.APPDATA || join(homedir, "AppData", "Roaming");
|
|
149
|
+
return join(appData, "filecafe", "config.json");
|
|
150
|
+
}
|
|
151
|
+
const xdg = env.XDG_CONFIG_HOME;
|
|
152
|
+
const base = xdg && xdg.startsWith("/") ? xdg : join(homedir, ".config");
|
|
153
|
+
return join(base, "filecafe", "config.json");
|
|
154
|
+
}
|
|
155
|
+
/** Validate and normalize a base URL (http/https only, no trailing slash). */
|
|
156
|
+
function normalizeBaseUrl(value) {
|
|
157
|
+
let url;
|
|
158
|
+
try {
|
|
159
|
+
url = new URL(value.trim());
|
|
160
|
+
} catch {
|
|
161
|
+
throw new Error(`Invalid URL "${value}". Expected something like https://file.cafe`);
|
|
162
|
+
}
|
|
163
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Invalid URL "${value}". Only http:// and https:// URLs are supported.`);
|
|
164
|
+
if (url.username || url.password || url.search || url.hash) throw new Error(`Invalid URL "${value}". Pass only the site address, e.g. https://file.cafe`);
|
|
165
|
+
return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
|
|
166
|
+
}
|
|
167
|
+
async function readConfig(environment) {
|
|
168
|
+
let raw;
|
|
169
|
+
try {
|
|
170
|
+
raw = await readFile(configPath(environment), "utf8");
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (error.code === "ENOENT") return null;
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
const parsed = JSON.parse(raw);
|
|
177
|
+
if (typeof parsed.url === "string" && typeof parsed.token === "string" && parsed.token) return {
|
|
178
|
+
url: normalizeBaseUrl(parsed.url),
|
|
179
|
+
token: parsed.token
|
|
180
|
+
};
|
|
181
|
+
} catch {}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
/** Write the config file atomically with owner-only permissions (dir 0700, file 0600). */
|
|
185
|
+
async function writeConfig(environment, config) {
|
|
186
|
+
const path = configPath(environment);
|
|
187
|
+
const directory = dirname(path);
|
|
188
|
+
await mkdir(directory, {
|
|
189
|
+
recursive: true,
|
|
190
|
+
mode: 448
|
|
191
|
+
});
|
|
192
|
+
if (environment.platform !== "win32") await chmod(directory, 448);
|
|
193
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
194
|
+
const contents = `${JSON.stringify({
|
|
195
|
+
url: config.url,
|
|
196
|
+
token: config.token
|
|
197
|
+
}, null, 2)}\n`;
|
|
198
|
+
await writeFile(temporary, contents, { mode: 384 });
|
|
199
|
+
await rename(temporary, path);
|
|
200
|
+
if (environment.platform !== "win32") await chmod(path, 384);
|
|
201
|
+
return path;
|
|
202
|
+
}
|
|
203
|
+
/** Delete the saved config. Returns true if a file was removed. */
|
|
204
|
+
async function deleteConfig(environment) {
|
|
205
|
+
const path = configPath(environment);
|
|
206
|
+
try {
|
|
207
|
+
await rm(path);
|
|
208
|
+
return true;
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error.code === "ENOENT") return false;
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Resolve the base URL and token.
|
|
216
|
+
*
|
|
217
|
+
* Base URL: --url, then FILECAFE_URL, then the URL saved by `filecafe login`, then https://file.cafe.
|
|
218
|
+
* Token: FILECAFE_TOKEN, then the saved token — but the saved token is only used when it was
|
|
219
|
+
* issued for the resolved base URL, so a token is never sent to a different site.
|
|
220
|
+
*/
|
|
221
|
+
async function resolveSettings(environment, urlOption) {
|
|
222
|
+
const saved = await readConfig(environment);
|
|
223
|
+
const baseUrl = normalizeBaseUrl(urlOption || environment.env.FILECAFE_URL || saved?.url || "https://file.cafe");
|
|
224
|
+
const envToken = environment.env.FILECAFE_TOKEN?.trim();
|
|
225
|
+
if (envToken) return {
|
|
226
|
+
baseUrl,
|
|
227
|
+
token: envToken,
|
|
228
|
+
tokenSource: "env",
|
|
229
|
+
saved
|
|
230
|
+
};
|
|
231
|
+
if (saved && saved.url === baseUrl) return {
|
|
232
|
+
baseUrl,
|
|
233
|
+
token: saved.token,
|
|
234
|
+
tokenSource: "config",
|
|
235
|
+
saved
|
|
236
|
+
};
|
|
237
|
+
return {
|
|
238
|
+
baseUrl,
|
|
239
|
+
token: null,
|
|
240
|
+
tokenSource: null,
|
|
241
|
+
saved
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
// src/version.ts
|
|
245
|
+
const VERSION = "0.1.1";
|
|
246
|
+
// src/context.ts
|
|
247
|
+
/** Open a URL in the default browser without ever throwing. */
|
|
248
|
+
function openBrowser(url, platform = process.platform) {
|
|
249
|
+
try {
|
|
250
|
+
const [command, args, extra] = platform === "darwin" ? [
|
|
251
|
+
"open",
|
|
252
|
+
[url],
|
|
253
|
+
{}
|
|
254
|
+
] : platform === "win32" ? [
|
|
255
|
+
"cmd",
|
|
256
|
+
[
|
|
257
|
+
"/c",
|
|
258
|
+
"start",
|
|
259
|
+
"\"\"",
|
|
260
|
+
url.replace(/&/g, "^&")
|
|
261
|
+
],
|
|
262
|
+
{ windowsVerbatimArguments: true }
|
|
263
|
+
] : [
|
|
264
|
+
"xdg-open",
|
|
265
|
+
[url],
|
|
266
|
+
{}
|
|
267
|
+
];
|
|
268
|
+
const child = spawn(command, args, {
|
|
269
|
+
stdio: "ignore",
|
|
270
|
+
detached: true,
|
|
271
|
+
...extra
|
|
272
|
+
});
|
|
273
|
+
child.on("error", () => {});
|
|
274
|
+
child.unref();
|
|
275
|
+
} catch {}
|
|
276
|
+
}
|
|
277
|
+
function createDefaultContext() {
|
|
278
|
+
return {
|
|
279
|
+
env: process.env,
|
|
280
|
+
platform: process.platform,
|
|
281
|
+
homedir: homedir(),
|
|
282
|
+
fetch: (input, init) => fetch(input, init),
|
|
283
|
+
sleep: (ms) => setTimeout$1(ms),
|
|
284
|
+
stdout: process.stdout,
|
|
285
|
+
stderr: process.stderr,
|
|
286
|
+
stdin: process.stdin,
|
|
287
|
+
openBrowser: (url) => openBrowser(url),
|
|
288
|
+
userAgent: `filecafe-cli/${VERSION} node/${process.versions.node} (${process.platform})`
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/** Thrown for expected failures; the message is printed as-is and the process exits with code 1. */
|
|
292
|
+
var CliError = class extends Error {
|
|
293
|
+
constructor(message) {
|
|
294
|
+
super(message);
|
|
295
|
+
this.name = "CliError";
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
// src/login-server.ts
|
|
299
|
+
const LOGIN_TIMEOUT_MS = 3e5;
|
|
300
|
+
function generateState() {
|
|
301
|
+
return randomBytes(16).toString("hex");
|
|
302
|
+
}
|
|
303
|
+
function statesMatch(received, expected) {
|
|
304
|
+
if (received === null) return false;
|
|
305
|
+
const a = Buffer.from(received, "utf8");
|
|
306
|
+
const b = Buffer.from(expected, "utf8");
|
|
307
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
308
|
+
}
|
|
309
|
+
function page(title, message) {
|
|
310
|
+
return `<!doctype html>
|
|
311
|
+
<html lang="en">
|
|
312
|
+
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title>
|
|
313
|
+
<style>body{font-family:system-ui,-apple-system,sans-serif;display:flex;min-height:100vh;margin:0;align-items:center;justify-content:center;background:#faf9f7;color:#1c1917}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem}p{color:#57534e}</style>
|
|
314
|
+
</head>
|
|
315
|
+
<body><main><h1>${title}</h1><p>${message}</p></main></body>
|
|
316
|
+
</html>
|
|
317
|
+
`;
|
|
318
|
+
}
|
|
319
|
+
const SUCCESS_PAGE = page("You're logged in to file.cafe.", "You can close this tab and return to your terminal.");
|
|
320
|
+
const DENIED_PAGE = page("Login cancelled.", "The file.cafe CLI was not authorized. You can close this tab.");
|
|
321
|
+
const FAILED_PAGE = page("Login failed.", "Something went wrong. Return to your terminal and run \"filecafe login\" again.");
|
|
322
|
+
const INVALID_PAGE = page("Invalid login request.", "This link does not match the login started in your terminal. Run \"filecafe login\" again.");
|
|
323
|
+
/**
|
|
324
|
+
* Decide how to answer a request to the local callback server. Only
|
|
325
|
+
* `GET /callback` with the expected `state` concludes the login; anything
|
|
326
|
+
* else is rejected and the server keeps waiting.
|
|
327
|
+
*/
|
|
328
|
+
function handleCallbackRequest(method, rawUrl, expectedState) {
|
|
329
|
+
const url = new URL(rawUrl ?? "/", "http://127.0.0.1");
|
|
330
|
+
if (method !== "GET" || url.pathname !== "/callback") return {
|
|
331
|
+
status: 404,
|
|
332
|
+
body: page("Not found.", "Nothing to see here.")
|
|
333
|
+
};
|
|
334
|
+
if (!statesMatch(url.searchParams.get("state"), expectedState)) return {
|
|
335
|
+
status: 400,
|
|
336
|
+
body: INVALID_PAGE
|
|
337
|
+
};
|
|
338
|
+
const error = url.searchParams.get("error");
|
|
339
|
+
if (error) return {
|
|
340
|
+
status: 200,
|
|
341
|
+
body: error === "access_denied" ? DENIED_PAGE : FAILED_PAGE,
|
|
342
|
+
result: { error }
|
|
343
|
+
};
|
|
344
|
+
const token = url.searchParams.get("token");
|
|
345
|
+
if (!token) return {
|
|
346
|
+
status: 400,
|
|
347
|
+
body: FAILED_PAGE
|
|
348
|
+
};
|
|
349
|
+
return {
|
|
350
|
+
status: 200,
|
|
351
|
+
body: SUCCESS_PAGE,
|
|
352
|
+
result: { token }
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
/** Listen on a random loopback port for the browser redirect. */
|
|
356
|
+
function startCallbackServer(state, timeoutMs = LOGIN_TIMEOUT_MS) {
|
|
357
|
+
let settle = () => {};
|
|
358
|
+
let fail = () => {};
|
|
359
|
+
let settled = false;
|
|
360
|
+
const result = new Promise((resolve, reject) => {
|
|
361
|
+
settle = resolve;
|
|
362
|
+
fail = reject;
|
|
363
|
+
});
|
|
364
|
+
const server = createServer((request, response) => {
|
|
365
|
+
const outcome = handleCallbackRequest(request.method, request.url, state);
|
|
366
|
+
response.writeHead(outcome.status, {
|
|
367
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
368
|
+
"Cache-Control": "no-store",
|
|
369
|
+
"Referrer-Policy": "no-referrer",
|
|
370
|
+
Connection: "close"
|
|
371
|
+
});
|
|
372
|
+
response.end(outcome.body);
|
|
373
|
+
if (outcome.result && !settled) {
|
|
374
|
+
const loginResult = outcome.result;
|
|
375
|
+
response.on("finish", () => finish(() => settle(loginResult)));
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
let timer;
|
|
379
|
+
const close = () => {
|
|
380
|
+
clearTimeout(timer);
|
|
381
|
+
server.close();
|
|
382
|
+
server.closeAllConnections();
|
|
383
|
+
};
|
|
384
|
+
const finish = (callback) => {
|
|
385
|
+
if (settled) return;
|
|
386
|
+
settled = true;
|
|
387
|
+
close();
|
|
388
|
+
callback();
|
|
389
|
+
};
|
|
390
|
+
return new Promise((resolve, reject) => {
|
|
391
|
+
server.once("error", reject);
|
|
392
|
+
server.listen(0, "127.0.0.1", () => {
|
|
393
|
+
const address = server.address();
|
|
394
|
+
if (!address || typeof address === "string") {
|
|
395
|
+
close();
|
|
396
|
+
reject(/* @__PURE__ */ new Error("Could not start the local login server."));
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
timer = setTimeout(() => finish(() => fail(/* @__PURE__ */ new Error("Timed out waiting for the browser login (5 minutes). Run \"filecafe login\" again, or use \"filecafe login --token <token>\"."))), timeoutMs);
|
|
400
|
+
resolve({
|
|
401
|
+
port: address.port,
|
|
402
|
+
result,
|
|
403
|
+
close: () => finish(() => fail(/* @__PURE__ */ new Error("Login cancelled.")))
|
|
404
|
+
});
|
|
405
|
+
});
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
// src/session.ts
|
|
409
|
+
const NOT_LOGGED_IN = "Not logged in. Run \"filecafe login\" or set FILECAFE_TOKEN.";
|
|
410
|
+
function clientFor(context, baseUrl, token, onNotice) {
|
|
411
|
+
return createApiClient({
|
|
412
|
+
baseUrl,
|
|
413
|
+
token,
|
|
414
|
+
fetch: context.fetch,
|
|
415
|
+
sleep: context.sleep,
|
|
416
|
+
userAgent: context.userAgent,
|
|
417
|
+
onNotice
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
/** Resolve the base URL and token, failing with a helpful message when not logged in. */
|
|
421
|
+
async function requireSession(context, globals, onNotice) {
|
|
422
|
+
let settings;
|
|
423
|
+
try {
|
|
424
|
+
settings = await resolveSettings(context, globals.url);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
throw new CliError(error.message);
|
|
427
|
+
}
|
|
428
|
+
const { token } = settings;
|
|
429
|
+
if (!token) {
|
|
430
|
+
if (settings.saved && settings.saved.url !== settings.baseUrl) throw new CliError(`Not logged in to ${settings.baseUrl} (the saved login is for ${settings.saved.url}). Run "filecafe login --url ${settings.baseUrl}" or set FILECAFE_TOKEN.`);
|
|
431
|
+
throw new CliError(NOT_LOGGED_IN);
|
|
432
|
+
}
|
|
433
|
+
return {
|
|
434
|
+
client: clientFor(context, settings.baseUrl, token, onNotice),
|
|
435
|
+
settings: {
|
|
436
|
+
...settings,
|
|
437
|
+
token
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
// src/commands/login.ts
|
|
442
|
+
async function readAll(input) {
|
|
443
|
+
let text = "";
|
|
444
|
+
for await (const chunk of input) text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
445
|
+
return text;
|
|
446
|
+
}
|
|
447
|
+
function authorizeUrl(baseUrl, port, state, name) {
|
|
448
|
+
return `${baseUrl}/cli/authorize?port=${port}&state=${state}&name=${encodeURIComponent(name)}`;
|
|
449
|
+
}
|
|
450
|
+
async function tokenFromBrowser(context, baseUrl, timeoutMs) {
|
|
451
|
+
const state = generateState();
|
|
452
|
+
const server = await startCallbackServer(state, timeoutMs);
|
|
453
|
+
const url = authorizeUrl(baseUrl, server.port, state, hostname());
|
|
454
|
+
context.stderr.write(`Opening your browser to log in to ${baseUrl}.\n`);
|
|
455
|
+
context.stderr.write(`If it does not open, visit this URL on this machine:\n\n ${url}\n\nWaiting for approval...\n`);
|
|
456
|
+
context.openBrowser(url);
|
|
457
|
+
const result = await server.result;
|
|
458
|
+
if ("error" in result) throw new CliError(result.error === "access_denied" ? "Login was cancelled in the browser." : `Login failed in the browser (${result.error}).`);
|
|
459
|
+
return result.token;
|
|
460
|
+
}
|
|
461
|
+
async function loginCommand(options, globals, context) {
|
|
462
|
+
if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
|
|
463
|
+
let baseUrl;
|
|
464
|
+
try {
|
|
465
|
+
baseUrl = normalizeBaseUrl(globals.url || context.env.FILECAFE_URL || "https://file.cafe");
|
|
466
|
+
} catch (error) {
|
|
467
|
+
throw new CliError(error.message);
|
|
468
|
+
}
|
|
469
|
+
let token;
|
|
470
|
+
if (options.token !== void 0) token = options.token.trim();
|
|
471
|
+
else if (options.withToken) {
|
|
472
|
+
if (context.stdin.isTTY) throw new CliError("--with-token reads the token from standard input, e.g.: echo \"$TOKEN\" | filecafe login --with-token");
|
|
473
|
+
token = (await readAll(context.stdin)).trim();
|
|
474
|
+
} else token = await tokenFromBrowser(context, baseUrl, options.timeoutMs ?? 3e5);
|
|
475
|
+
if (!token || /\s/.test(token)) throw new CliError("The token is empty or malformed.");
|
|
476
|
+
let me;
|
|
477
|
+
try {
|
|
478
|
+
me = await fetchMe(clientFor(context, baseUrl, token));
|
|
479
|
+
} catch (error) {
|
|
480
|
+
if (error.status === 401) throw new CliError(`That token was rejected by ${baseUrl}. Check that it is correct and has not been revoked.`);
|
|
481
|
+
throw new CliError(error.message);
|
|
482
|
+
}
|
|
483
|
+
await writeConfig(context, {
|
|
484
|
+
url: baseUrl,
|
|
485
|
+
token
|
|
486
|
+
});
|
|
487
|
+
context.stdout.write(`Logged in as ${me.name} (${me.email})\n`);
|
|
488
|
+
context.stderr.write(`Saved credentials for ${baseUrl} to ${configPath(context)}\n`);
|
|
489
|
+
if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write("Note: FILECAFE_TOKEN is set in your environment and takes precedence over the saved login.\n");
|
|
490
|
+
return 0;
|
|
491
|
+
}
|
|
492
|
+
// src/commands/logout.ts
|
|
493
|
+
async function logoutCommand(context) {
|
|
494
|
+
const saved = await readConfig(context).catch(() => null);
|
|
495
|
+
if (saved) try {
|
|
496
|
+
await clientFor(context, saved.url, saved.token).request("DELETE", "/api/v1/token", void 0, { idempotent: true });
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (!(error instanceof ApiError && error.status === 401)) context.stderr.write(`Could not revoke the token on ${saved.url}: ${error.message}\nIt may still be active; revoke it in Settings → API tokens.\n`);
|
|
499
|
+
}
|
|
500
|
+
if (await deleteConfig(context)) {
|
|
501
|
+
context.stdout.write(saved ? `Logged out of ${saved.url}.\n` : "Logged out.\n");
|
|
502
|
+
context.stderr.write(`Removed ${configPath(context)}\n`);
|
|
503
|
+
} else context.stdout.write("Not logged in; nothing to do.\n");
|
|
504
|
+
if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write("Note: FILECAFE_TOKEN is still set in your environment; unset it to stop using that token.\n");
|
|
505
|
+
return 0;
|
|
506
|
+
}
|
|
507
|
+
// src/mime.ts
|
|
508
|
+
/**
|
|
509
|
+
* A deliberately small extension → MIME type map. The server re-detects the
|
|
510
|
+
* real type from the uploaded bytes, so this only needs to be plausible.
|
|
511
|
+
*/
|
|
512
|
+
const MIME_TYPES = {
|
|
513
|
+
png: "image/png",
|
|
514
|
+
jpg: "image/jpeg",
|
|
515
|
+
jpeg: "image/jpeg",
|
|
516
|
+
gif: "image/gif",
|
|
517
|
+
webp: "image/webp",
|
|
518
|
+
avif: "image/avif",
|
|
519
|
+
heic: "image/heic",
|
|
520
|
+
heif: "image/heif",
|
|
521
|
+
bmp: "image/bmp",
|
|
522
|
+
tif: "image/tiff",
|
|
523
|
+
tiff: "image/tiff",
|
|
524
|
+
ico: "image/vnd.microsoft.icon",
|
|
525
|
+
svg: "image/svg+xml",
|
|
526
|
+
psd: "image/vnd.adobe.photoshop",
|
|
527
|
+
mp4: "video/mp4",
|
|
528
|
+
m4v: "video/x-m4v",
|
|
529
|
+
mov: "video/quicktime",
|
|
530
|
+
webm: "video/webm",
|
|
531
|
+
mkv: "video/x-matroska",
|
|
532
|
+
avi: "video/x-msvideo",
|
|
533
|
+
wmv: "video/x-ms-wmv",
|
|
534
|
+
mpeg: "video/mpeg",
|
|
535
|
+
mpg: "video/mpeg",
|
|
536
|
+
"3gp": "video/3gpp",
|
|
537
|
+
mp3: "audio/mpeg",
|
|
538
|
+
wav: "audio/wav",
|
|
539
|
+
ogg: "audio/ogg",
|
|
540
|
+
oga: "audio/ogg",
|
|
541
|
+
opus: "audio/opus",
|
|
542
|
+
flac: "audio/flac",
|
|
543
|
+
aac: "audio/aac",
|
|
544
|
+
m4a: "audio/mp4",
|
|
545
|
+
weba: "audio/webm",
|
|
546
|
+
aiff: "audio/aiff",
|
|
547
|
+
mid: "audio/midi",
|
|
548
|
+
midi: "audio/midi",
|
|
549
|
+
pdf: "application/pdf",
|
|
550
|
+
doc: "application/msword",
|
|
551
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
552
|
+
xls: "application/vnd.ms-excel",
|
|
553
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
554
|
+
ppt: "application/vnd.ms-powerpoint",
|
|
555
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
556
|
+
odt: "application/vnd.oasis.opendocument.text",
|
|
557
|
+
ods: "application/vnd.oasis.opendocument.spreadsheet",
|
|
558
|
+
odp: "application/vnd.oasis.opendocument.presentation",
|
|
559
|
+
rtf: "application/rtf",
|
|
560
|
+
epub: "application/epub+zip",
|
|
561
|
+
key: "application/vnd.apple.keynote",
|
|
562
|
+
pages: "application/vnd.apple.pages",
|
|
563
|
+
numbers: "application/vnd.apple.numbers",
|
|
564
|
+
zip: "application/zip",
|
|
565
|
+
gz: "application/gzip",
|
|
566
|
+
tgz: "application/gzip",
|
|
567
|
+
tar: "application/x-tar",
|
|
568
|
+
bz2: "application/x-bzip2",
|
|
569
|
+
xz: "application/x-xz",
|
|
570
|
+
"7z": "application/x-7z-compressed",
|
|
571
|
+
rar: "application/vnd.rar",
|
|
572
|
+
zst: "application/zstd",
|
|
573
|
+
dmg: "application/x-apple-diskimage",
|
|
574
|
+
iso: "application/x-iso9660-image",
|
|
575
|
+
apk: "application/vnd.android.package-archive",
|
|
576
|
+
wasm: "application/wasm",
|
|
577
|
+
woff: "font/woff",
|
|
578
|
+
woff2: "font/woff2",
|
|
579
|
+
ttf: "font/ttf",
|
|
580
|
+
otf: "font/otf",
|
|
581
|
+
txt: "text/plain",
|
|
582
|
+
log: "text/plain",
|
|
583
|
+
md: "text/markdown",
|
|
584
|
+
markdown: "text/markdown",
|
|
585
|
+
csv: "text/csv",
|
|
586
|
+
tsv: "text/tab-separated-values",
|
|
587
|
+
html: "text/html",
|
|
588
|
+
htm: "text/html",
|
|
589
|
+
css: "text/css",
|
|
590
|
+
xml: "application/xml",
|
|
591
|
+
json: "application/json",
|
|
592
|
+
jsonl: "application/jsonl",
|
|
593
|
+
ndjson: "application/x-ndjson",
|
|
594
|
+
yaml: "application/yaml",
|
|
595
|
+
yml: "application/yaml",
|
|
596
|
+
toml: "application/toml",
|
|
597
|
+
ini: "text/plain",
|
|
598
|
+
js: "text/javascript",
|
|
599
|
+
mjs: "text/javascript",
|
|
600
|
+
cjs: "text/javascript",
|
|
601
|
+
jsx: "text/javascript",
|
|
602
|
+
ts: "text/x-typescript",
|
|
603
|
+
tsx: "text/x-typescript",
|
|
604
|
+
py: "text/x-python",
|
|
605
|
+
rb: "text/x-ruby",
|
|
606
|
+
php: "text/x-php",
|
|
607
|
+
go: "text/x-go",
|
|
608
|
+
rs: "text/x-rust",
|
|
609
|
+
java: "text/x-java",
|
|
610
|
+
kt: "text/x-kotlin",
|
|
611
|
+
swift: "text/x-swift",
|
|
612
|
+
c: "text/x-c",
|
|
613
|
+
h: "text/x-c",
|
|
614
|
+
cc: "text/x-c++",
|
|
615
|
+
cpp: "text/x-c++",
|
|
616
|
+
hpp: "text/x-c++",
|
|
617
|
+
cs: "text/x-csharp",
|
|
618
|
+
sh: "application/x-sh",
|
|
619
|
+
bash: "application/x-sh",
|
|
620
|
+
zsh: "application/x-sh",
|
|
621
|
+
sql: "application/sql",
|
|
622
|
+
diff: "text/x-diff",
|
|
623
|
+
patch: "text/x-diff",
|
|
624
|
+
vtt: "text/vtt",
|
|
625
|
+
srt: "application/x-subrip",
|
|
626
|
+
ics: "text/calendar"
|
|
627
|
+
};
|
|
628
|
+
/** Guess a MIME type from a file name's extension. */
|
|
629
|
+
function guessMimeType(filename) {
|
|
630
|
+
const extension = extname(filename).slice(1).toLowerCase();
|
|
631
|
+
return extension && MIME_TYPES[extension] || "application/octet-stream";
|
|
632
|
+
}
|
|
633
|
+
// src/upload.ts
|
|
634
|
+
/** An error while transferring bytes to the upload server. */
|
|
635
|
+
var TransferError = class extends Error {
|
|
636
|
+
status;
|
|
637
|
+
/** The upload must be started again from scratch (e.g. the receipt for a written object was lost). */
|
|
638
|
+
restartUpload;
|
|
639
|
+
constructor(message, status, restartUpload = false) {
|
|
640
|
+
super(message);
|
|
641
|
+
this.name = "TransferError";
|
|
642
|
+
this.status = status;
|
|
643
|
+
this.restartUpload = restartUpload;
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
const DEFAULT_CONCURRENCY = 4;
|
|
647
|
+
const DEFAULT_PART_RETRIES = 3;
|
|
648
|
+
const DEFAULT_PART_TIMEOUT_MS = 9e5;
|
|
649
|
+
function isRecord(value) {
|
|
650
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
651
|
+
}
|
|
652
|
+
function isSignedTarget(value) {
|
|
653
|
+
return isRecord(value) && typeof value.url === "string" && isRecord(value.headers) && Object.values(value.headers).every((header) => typeof header === "string");
|
|
654
|
+
}
|
|
655
|
+
/** Validate the start response and turn it into a list of byte ranges to PUT. */
|
|
656
|
+
function planTransfer(upload, size) {
|
|
657
|
+
const unexpected = (detail) => new ApiError(`Unexpected response when starting the upload: ${detail}.`, null);
|
|
658
|
+
const data = upload;
|
|
659
|
+
if (!isRecord(data) || typeof data.id !== "string" || typeof data.token !== "string") throw unexpected("missing id or token");
|
|
660
|
+
if ("parts" in data) {
|
|
661
|
+
const { parts, part_size: partSize } = data;
|
|
662
|
+
if (typeof partSize !== "number" || !Number.isSafeInteger(partSize) || partSize <= 0) throw unexpected("invalid part_size");
|
|
663
|
+
if (!Array.isArray(parts) || !parts.every(isSignedTarget)) throw unexpected("invalid parts");
|
|
664
|
+
const expectedParts = Math.max(1, Math.ceil(size / partSize));
|
|
665
|
+
if (parts.length !== expectedParts) throw unexpected(`expected ${expectedParts} parts but got ${parts.length}`);
|
|
666
|
+
return {
|
|
667
|
+
targets: parts,
|
|
668
|
+
partSize
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
if (!isSignedTarget(data)) throw unexpected("missing upload url");
|
|
672
|
+
return {
|
|
673
|
+
targets: [{
|
|
674
|
+
url: data.url,
|
|
675
|
+
headers: data.headers
|
|
676
|
+
}],
|
|
677
|
+
partSize: Math.max(size, 1)
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
function describeFetchError(error) {
|
|
681
|
+
if (error instanceof Error) {
|
|
682
|
+
if (error.name === "TimeoutError") return "timed out";
|
|
683
|
+
const cause = error.cause;
|
|
684
|
+
if (cause && typeof cause.code === "string") return cause.code;
|
|
685
|
+
if (cause && typeof cause.message === "string") return cause.message;
|
|
686
|
+
return error.message;
|
|
687
|
+
}
|
|
688
|
+
return String(error);
|
|
689
|
+
}
|
|
690
|
+
/** PUT one byte range, retrying network errors and 5xx responses. Returns the upload receipt. */
|
|
691
|
+
async function putPart(target, body, options) {
|
|
692
|
+
for (let attempt = 0;; attempt++) {
|
|
693
|
+
options.signal.throwIfAborted();
|
|
694
|
+
let response;
|
|
695
|
+
try {
|
|
696
|
+
response = await options.fetch(target.url, {
|
|
697
|
+
method: "PUT",
|
|
698
|
+
headers: target.headers,
|
|
699
|
+
body,
|
|
700
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
|
|
701
|
+
});
|
|
702
|
+
} catch (error) {
|
|
703
|
+
if (options.signal.aborted) throw options.signal.reason;
|
|
704
|
+
if (attempt < options.maxRetries) {
|
|
705
|
+
await options.sleep(1e3 * 2 ** attempt);
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
throw new TransferError(`Upload of ${options.label} failed: network error (${describeFetchError(error)}).`, null);
|
|
709
|
+
}
|
|
710
|
+
if (response.ok) {
|
|
711
|
+
await response.body?.cancel();
|
|
712
|
+
const receipt = response.headers.get("X-Upload-Receipt");
|
|
713
|
+
if (!receipt && options.requireReceipt) throw new TransferError(`Upload of ${options.label} succeeded but the server did not return an upload receipt.`, response.status);
|
|
714
|
+
return receipt;
|
|
715
|
+
}
|
|
716
|
+
const detail = (await response.text().catch(() => "")).trim().slice(0, 500);
|
|
717
|
+
if (response.status === 412) throw new TransferError(`Upload of ${options.label} failed: the file already exists and its receipt was lost.`, 412, true);
|
|
718
|
+
if (response.status >= 500 && attempt < options.maxRetries) {
|
|
719
|
+
await options.sleep(1e3 * 2 ** attempt);
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
throw new TransferError(`Upload of ${options.label} failed (HTTP ${response.status})${detail ? `: ${detail}` : "."}`, response.status);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
/** Run `worker` for indexes 0..count-1 with bounded concurrency, stopping on the first error. */
|
|
726
|
+
async function runPool(count, concurrency, controller, worker) {
|
|
727
|
+
let next = 0;
|
|
728
|
+
let firstError = null;
|
|
729
|
+
const runner = async () => {
|
|
730
|
+
while (next < count && !controller.signal.aborted) {
|
|
731
|
+
const index = next++;
|
|
732
|
+
try {
|
|
733
|
+
await worker(index);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
if (firstError === null) {
|
|
736
|
+
firstError = error;
|
|
737
|
+
controller.abort(error);
|
|
738
|
+
}
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, count)) }, runner));
|
|
744
|
+
if (firstError !== null) throw firstError;
|
|
745
|
+
}
|
|
746
|
+
async function transferOnce(options, blob) {
|
|
747
|
+
const { client, size } = options;
|
|
748
|
+
const started = await client.request("POST", "/api/v1/uploads", {
|
|
749
|
+
filename: options.filename,
|
|
750
|
+
size,
|
|
751
|
+
mime_type: options.mimeType,
|
|
752
|
+
...options.collectionId ? { collection_id: options.collectionId } : {}
|
|
753
|
+
});
|
|
754
|
+
const { targets, partSize } = planTransfer(started, size);
|
|
755
|
+
const requireReceipt = started.requires_receipts !== false;
|
|
756
|
+
const receipts = new Array(targets.length).fill(null);
|
|
757
|
+
const controller = new AbortController();
|
|
758
|
+
let uploadedBytes = 0;
|
|
759
|
+
options.onProgress?.(0, size);
|
|
760
|
+
await runPool(targets.length, options.concurrency ?? DEFAULT_CONCURRENCY, controller, async (index) => {
|
|
761
|
+
const start = index * partSize;
|
|
762
|
+
const end = Math.min(start + partSize, size);
|
|
763
|
+
const target = targets[index];
|
|
764
|
+
receipts[index] = await putPart(target, blob.slice(start, end), {
|
|
765
|
+
fetch: options.fetch,
|
|
766
|
+
sleep: options.sleep,
|
|
767
|
+
maxRetries: options.maxPartRetries ?? DEFAULT_PART_RETRIES,
|
|
768
|
+
timeoutMs: options.partTimeoutMs ?? DEFAULT_PART_TIMEOUT_MS,
|
|
769
|
+
signal: controller.signal,
|
|
770
|
+
requireReceipt,
|
|
771
|
+
label: targets.length > 1 ? `part ${index + 1}/${targets.length}` : options.filename
|
|
772
|
+
});
|
|
773
|
+
uploadedBytes += end - start;
|
|
774
|
+
options.onProgress?.(uploadedBytes, size);
|
|
775
|
+
});
|
|
776
|
+
return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, {
|
|
777
|
+
token: started.token,
|
|
778
|
+
receipts: receipts.filter((receipt) => receipt !== null)
|
|
779
|
+
}, { idempotent: true });
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Upload one file: start the upload, PUT each part (in parallel for multipart),
|
|
783
|
+
* then complete it with the receipts in part order.
|
|
784
|
+
*/
|
|
785
|
+
async function uploadFile(options) {
|
|
786
|
+
const blob = await openAsBlob(options.path);
|
|
787
|
+
if (blob.size !== options.size) throw new Error(`${options.path} changed size while uploading. Please retry.`);
|
|
788
|
+
try {
|
|
789
|
+
return await transferOnce(options, blob);
|
|
790
|
+
} catch (error) {
|
|
791
|
+
if (error instanceof TransferError && error.restartUpload) {
|
|
792
|
+
options.onNotice?.(`Restarting the upload of ${options.filename}...`);
|
|
793
|
+
return transferOnce(options, blob);
|
|
794
|
+
}
|
|
795
|
+
throw error;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
// src/commands/upload.ts
|
|
799
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
800
|
+
const MAX_FILENAME_LENGTH = 255;
|
|
801
|
+
/** The name sent to the server: a basename without slashes or control characters, at most 255 characters. */
|
|
802
|
+
function uploadFilename(path) {
|
|
803
|
+
let name = basename(path).replace(/[\u0000-\u001f\u007f\\/]/g, "_").trim();
|
|
804
|
+
if (!name || name === "." || name === "..") name = "file";
|
|
805
|
+
const characters = Array.from(name);
|
|
806
|
+
if (characters.length <= MAX_FILENAME_LENGTH) return name;
|
|
807
|
+
const extension = Array.from(extname(name));
|
|
808
|
+
const keep = extension.length > 0 && extension.length <= 16 ? extension : [];
|
|
809
|
+
return characters.slice(0, MAX_FILENAME_LENGTH - keep.length).join("") + keep.join("");
|
|
810
|
+
}
|
|
811
|
+
function formatBytes(bytes) {
|
|
812
|
+
const units = [
|
|
813
|
+
"B",
|
|
814
|
+
"KB",
|
|
815
|
+
"MB",
|
|
816
|
+
"GB",
|
|
817
|
+
"TB"
|
|
818
|
+
];
|
|
819
|
+
let value = bytes;
|
|
820
|
+
let unit = 0;
|
|
821
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
822
|
+
value /= 1024;
|
|
823
|
+
unit++;
|
|
824
|
+
}
|
|
825
|
+
return unit === 0 ? `${value} ${units[unit]}` : `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
|
|
826
|
+
}
|
|
827
|
+
async function validateFile(file) {
|
|
828
|
+
try {
|
|
829
|
+
const stats = await stat(file);
|
|
830
|
+
if (stats.isDirectory()) return {
|
|
831
|
+
file,
|
|
832
|
+
error: "Is a directory. Only regular files can be uploaded."
|
|
833
|
+
};
|
|
834
|
+
if (!stats.isFile()) return {
|
|
835
|
+
file,
|
|
836
|
+
error: "Not a regular file."
|
|
837
|
+
};
|
|
838
|
+
return {
|
|
839
|
+
file,
|
|
840
|
+
size: stats.size
|
|
841
|
+
};
|
|
842
|
+
} catch (error) {
|
|
843
|
+
const code = error.code;
|
|
844
|
+
if (code === "ENOENT") return {
|
|
845
|
+
file,
|
|
846
|
+
error: "No such file."
|
|
847
|
+
};
|
|
848
|
+
if (code === "EACCES" || code === "EPERM") return {
|
|
849
|
+
file,
|
|
850
|
+
error: "Permission denied."
|
|
851
|
+
};
|
|
852
|
+
return {
|
|
853
|
+
file,
|
|
854
|
+
error: error.message
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
function createProgress(context, enabled) {
|
|
859
|
+
let active = false;
|
|
860
|
+
return {
|
|
861
|
+
update(line) {
|
|
862
|
+
if (!enabled) return;
|
|
863
|
+
active = true;
|
|
864
|
+
context.stderr.write(`\r\u001b[2K${line}`);
|
|
865
|
+
},
|
|
866
|
+
clear() {
|
|
867
|
+
if (enabled && active) {
|
|
868
|
+
context.stderr.write("\r\x1B[2K");
|
|
869
|
+
active = false;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
async function uploadCommand(files, options, globals, context) {
|
|
875
|
+
if (options.collection !== void 0 && !UUID_PATTERN.test(options.collection)) throw new CliError(`Invalid --collection "${options.collection}". Expected a collection UUID.`);
|
|
876
|
+
if (files.length === 0) throw new CliError("No files given. Usage: filecafe upload <files...>");
|
|
877
|
+
const progress = createProgress(context, Boolean(context.stderr.isTTY) && !options.json && !options.quiet);
|
|
878
|
+
const notice = (message) => {
|
|
879
|
+
if (!options.quiet) {
|
|
880
|
+
progress.clear();
|
|
881
|
+
context.stderr.write(`${message}\n`);
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
const { client } = await requireSession(context, globals, notice);
|
|
885
|
+
const checked = await Promise.all(files.map(validateFile));
|
|
886
|
+
const invalid = checked.filter((entry) => "error" in entry);
|
|
887
|
+
const results = [];
|
|
888
|
+
if (invalid.length > 0) for (const entry of checked) results.push({
|
|
889
|
+
file: entry.file,
|
|
890
|
+
ok: false,
|
|
891
|
+
error: "error" in entry ? entry.error : "Skipped because another input file is invalid; nothing was uploaded."
|
|
892
|
+
});
|
|
893
|
+
else {
|
|
894
|
+
let fatal = null;
|
|
895
|
+
for (const { file, size } of checked) {
|
|
896
|
+
let result;
|
|
897
|
+
if (fatal !== null) result = {
|
|
898
|
+
file,
|
|
899
|
+
ok: false,
|
|
900
|
+
error: fatal
|
|
901
|
+
};
|
|
902
|
+
else {
|
|
903
|
+
const filename = uploadFilename(file);
|
|
904
|
+
progress.update(`Uploading ${filename} (${formatBytes(size)})...`);
|
|
905
|
+
try {
|
|
906
|
+
const completed = await uploadFile({
|
|
907
|
+
client,
|
|
908
|
+
fetch: context.fetch,
|
|
909
|
+
sleep: context.sleep,
|
|
910
|
+
path: file,
|
|
911
|
+
filename,
|
|
912
|
+
size,
|
|
913
|
+
mimeType: guessMimeType(filename),
|
|
914
|
+
collectionId: options.collection,
|
|
915
|
+
concurrency: options.concurrency,
|
|
916
|
+
onNotice: notice,
|
|
917
|
+
onProgress: (uploaded, total) => {
|
|
918
|
+
if (uploaded > 0 && total > 0) {
|
|
919
|
+
const percent = Math.floor(uploaded / total * 100);
|
|
920
|
+
progress.update(`Uploading ${filename} ${percent}% (${formatBytes(uploaded)} / ${formatBytes(total)})`);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
});
|
|
924
|
+
result = {
|
|
925
|
+
file,
|
|
926
|
+
ok: true,
|
|
927
|
+
id: completed.id,
|
|
928
|
+
filename: completed.filename,
|
|
929
|
+
size: completed.size,
|
|
930
|
+
url: completed.url ?? null,
|
|
931
|
+
password_protected: Boolean(completed.password_protected)
|
|
932
|
+
};
|
|
933
|
+
} catch (error) {
|
|
934
|
+
result = {
|
|
935
|
+
file,
|
|
936
|
+
ok: false,
|
|
937
|
+
error: error instanceof Error ? error.message : String(error)
|
|
938
|
+
};
|
|
939
|
+
if (error instanceof ApiError && error.isFatal) fatal = result.error;
|
|
940
|
+
} finally {
|
|
941
|
+
progress.clear();
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
results.push(result);
|
|
945
|
+
if (!options.json) {
|
|
946
|
+
if (result.ok && result.url) context.stdout.write(`${result.url}\n`);
|
|
947
|
+
else if (result.ok) context.stderr.write(`${file}: uploaded (id ${result.id}), but the server returned no share link.\n`);
|
|
948
|
+
else context.stderr.write(`${file}: ${result.error}\n`);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
if (options.json) context.stdout.write(`${JSON.stringify(results, null, 2)}\n`);
|
|
953
|
+
else if (invalid.length > 0) {
|
|
954
|
+
for (const entry of invalid) context.stderr.write(`${entry.file}: ${entry.error}\n`);
|
|
955
|
+
context.stderr.write("Nothing was uploaded.\n");
|
|
956
|
+
}
|
|
957
|
+
return results.every((result) => result.ok) ? 0 : 1;
|
|
958
|
+
}
|
|
959
|
+
// src/commands/whoami.ts
|
|
960
|
+
async function whoamiCommand(options, globals, context) {
|
|
961
|
+
const { client, settings } = await requireSession(context, globals);
|
|
962
|
+
let me;
|
|
963
|
+
try {
|
|
964
|
+
me = await fetchMe(client);
|
|
965
|
+
} catch (error) {
|
|
966
|
+
throw new CliError(error.message);
|
|
967
|
+
}
|
|
968
|
+
if (options.json) context.stdout.write(`${JSON.stringify({
|
|
969
|
+
name: me.name,
|
|
970
|
+
email: me.email,
|
|
971
|
+
url: settings.baseUrl,
|
|
972
|
+
token_source: settings.tokenSource
|
|
973
|
+
})}\n`);
|
|
974
|
+
else {
|
|
975
|
+
context.stdout.write(`Logged in to ${settings.baseUrl} as ${me.name} (${me.email})\n`);
|
|
976
|
+
if (settings.tokenSource === "env") context.stderr.write("(using FILECAFE_TOKEN)\n");
|
|
977
|
+
}
|
|
978
|
+
return 0;
|
|
979
|
+
}
|
|
980
|
+
// src/cli.ts
|
|
981
|
+
const MAIN_EXAMPLES = `
|
|
982
|
+
Examples:
|
|
983
|
+
$ filecafe login # log in via your browser (one time)
|
|
984
|
+
$ filecafe upload report.pdf # prints the share URL on stdout
|
|
985
|
+
$ filecafe upload a.png b.mp4 --json # machine-readable results (for scripts and AI agents)
|
|
986
|
+
$ filecafe upload ./build.zip | pbcopy # copy the share URL to the clipboard
|
|
987
|
+
$ FILECAFE_TOKEN=... npx filecafe upload notes.txt --json # CI / headless
|
|
988
|
+
|
|
989
|
+
Environment:
|
|
990
|
+
FILECAFE_TOKEN API token; takes precedence over the saved login
|
|
991
|
+
FILECAFE_URL Site URL (default: https://file.cafe)
|
|
992
|
+
|
|
993
|
+
Exit codes: 0 on success, 1 on any failure. Errors and progress go to stderr.
|
|
994
|
+
`;
|
|
995
|
+
const UPLOAD_EXAMPLES = `
|
|
996
|
+
Output:
|
|
997
|
+
Default: one share URL per line on stdout, in the order the files were given.
|
|
998
|
+
--json: a JSON array on stdout with one object per input file:
|
|
999
|
+
{"file": "a.png", "ok": true, "id": "...", "filename": "a.png",
|
|
1000
|
+
"size": 1234, "url": "https://file.cafe/...", "password_protected": false}
|
|
1001
|
+
{"file": "b.png", "ok": false, "error": "No such file."}
|
|
1002
|
+
Exit code is 0 if every file uploaded, 1 if any failed.
|
|
1003
|
+
|
|
1004
|
+
Examples:
|
|
1005
|
+
$ filecafe upload screenshot.png
|
|
1006
|
+
$ filecafe upload report.pdf data.csv --json
|
|
1007
|
+
$ filecafe upload video.mp4 --collection 0b6f9a2e-3c1d-4f7a-9e5b-2d8c4a1f6e3b
|
|
1008
|
+
$ filecafe upload build.zip --quiet | pbcopy
|
|
1009
|
+
$ FILECAFE_TOKEN=... filecafe upload logs.txt --json # no saved login needed
|
|
1010
|
+
`;
|
|
1011
|
+
const LOGIN_EXAMPLES = `
|
|
1012
|
+
Examples:
|
|
1013
|
+
$ filecafe login # opens your browser to approve this device
|
|
1014
|
+
$ echo "$FILECAFE_TOKEN" | filecafe login --with-token
|
|
1015
|
+
$ filecafe login --url http://file-cafe.test # log in to another file.cafe server
|
|
1016
|
+
|
|
1017
|
+
In CI you can skip login entirely and set FILECAFE_TOKEN instead.
|
|
1018
|
+
`;
|
|
1019
|
+
async function execute(context, action) {
|
|
1020
|
+
try {
|
|
1021
|
+
process.exitCode = await action();
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
const message = error instanceof CliError || error instanceof ApiError ? error.message : `Unexpected error: ${error instanceof Error ? error.message : String(error)}`;
|
|
1024
|
+
context.stderr.write(`${message}\n`);
|
|
1025
|
+
if (context.env.FILECAFE_DEBUG && error instanceof Error && error.stack) context.stderr.write(`${error.stack}\n`);
|
|
1026
|
+
process.exitCode = 1;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
function createProgram(context) {
|
|
1030
|
+
const program = new Command();
|
|
1031
|
+
program.name("filecafe").description("Upload files to file.cafe and get share links. Designed for AI coding agents, humans, and CI.").version(VERSION, "-v, --version", "print the version").option("--url <url>", "file.cafe site URL (env: FILECAFE_URL, default: https://file.cafe)").helpOption("-h, --help", "show help").showHelpAfterError("(run \"filecafe --help\" for usage and examples)").addHelpText("after", MAIN_EXAMPLES);
|
|
1032
|
+
const globals = (command) => command.optsWithGlobals();
|
|
1033
|
+
program.command("login").description("Log in via your browser, or save an existing API token").option("--token <token>", "save this API token instead of opening a browser (visible in shell history; prefer --with-token)").option("--with-token", "read the API token from standard input").addHelpText("after", LOGIN_EXAMPLES).action((options, command) => execute(context, () => loginCommand(options, globals(command), context)));
|
|
1034
|
+
program.command("logout").description("Revoke the saved login token on file.cafe and delete it from this machine (does not affect FILECAFE_TOKEN)").addHelpText("after", "\nThe token is revoked even if it was saved with \"filecafe login --token\", so don't log out\nwith a token that CI or another machine still uses.\n").action(() => execute(context, () => logoutCommand(context)));
|
|
1035
|
+
program.command("whoami").description("Show the account you are logged in as").option("--json", "print {\"name\",\"email\",\"url\",\"token_source\"} as JSON").addHelpText("after", "\nExamples:\n $ filecafe whoami\n $ filecafe whoami --json\n").action((options, command) => execute(context, () => whoamiCommand(options, globals(command), context)));
|
|
1036
|
+
program.command("upload").description("Upload one or more files and print their share URLs").argument("<files...>", "files to upload (uploaded one after another)").option("--collection <uuid>", "add the files to this collection").option("--json", "print a JSON array of per-file results on stdout").option("-q, --quiet", "no progress or notices on stderr (errors are still printed)").addHelpText("after", UPLOAD_EXAMPLES).action((files, options, command) => execute(context, () => uploadCommand(files, options, globals(command), context)));
|
|
1037
|
+
return program;
|
|
1038
|
+
}
|
|
1039
|
+
await createProgram(createDefaultContext()).parseAsync(process.argv);
|
|
1040
|
+
export { createProgram };
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "filecafe",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Upload files to file.cafe from the command line. Built for AI coding agents, humans, and CI.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"file.cafe",
|
|
7
|
+
"file-sharing",
|
|
8
|
+
"upload",
|
|
9
|
+
"cli",
|
|
10
|
+
"ai-agents"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://file.cafe",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"bin": {
|
|
15
|
+
"filecafe": "dist/cli.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=20"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsdown",
|
|
25
|
+
"dev": "node src/cli.ts",
|
|
26
|
+
"test": "node --test \"test/**/*.test.ts\"",
|
|
27
|
+
"typecheck": "tsc --noEmit",
|
|
28
|
+
"prepublishOnly": "npm run build && npm test"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"commander": "^14.0.3"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@types/node": "^24.19.2",
|
|
35
|
+
"tsdown": "^0.23.1",
|
|
36
|
+
"typescript": "^7.0.2"
|
|
37
|
+
},
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/filecafe/cli.git"
|
|
41
|
+
}
|
|
42
|
+
}
|