filecafe 0.1.0 → 0.2.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.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +50 -135
  3. package/package.json +5 -1
package/README.md CHANGED
@@ -27,7 +27,7 @@ Requires Node.js 20 or newer.
27
27
  filecafe login
28
28
  ```
29
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.
30
+ This shows a one-time code and opens your browser so you can approve the CLI on file.cafe; check that the code on the page matches the one in your terminal. It works over SSH too: if no browser opens, visit the printed URL on any device and enter the code. 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
31
 
32
32
  Headless machines and CI can use an existing token instead:
33
33
 
package/dist/cli.js CHANGED
@@ -4,9 +4,7 @@ import { homedir, hostname } from "node:os";
4
4
  import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, extname, join } from "node:path";
6
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";
7
+ import { setTimeout } from "node:timers/promises";
10
8
  import { openAsBlob } from "node:fs";
11
9
  // src/api.ts
12
10
  const LOGIN_HINT = "Run \"filecafe login\" or set FILECAFE_TOKEN.";
@@ -77,11 +75,12 @@ function createApiClient(options) {
77
75
  for (;;) {
78
76
  const headers = {
79
77
  Accept: "application/json",
80
- Authorization: `Bearer ${token}`,
78
+ ...token && { Authorization: `Bearer ${token}` },
81
79
  "User-Agent": userAgent
82
80
  };
83
81
  if (body !== void 0) headers["Content-Type"] = "application/json";
84
82
  let response;
83
+ let text;
85
84
  try {
86
85
  response = await fetch(url, {
87
86
  method,
@@ -90,6 +89,7 @@ function createApiClient(options) {
90
89
  redirect: "manual",
91
90
  signal: AbortSignal.timeout(timeoutMs)
92
91
  });
92
+ text = await response.text();
93
93
  } catch (error) {
94
94
  if (requestOptions.idempotent && networkRetries < maxNetworkRetries) {
95
95
  networkRetries++;
@@ -98,12 +98,7 @@ function createApiClient(options) {
98
98
  }
99
99
  throw new ApiError(`Could not reach ${baseUrl} (${describeNetworkError(error)}).`, null);
100
100
  }
101
- if (response.status >= 300 && response.status < 400) {
102
- const location = response.headers.get("Location");
103
- await response.body?.cancel();
104
- throw new ApiError(`${url} redirected to ${location ?? "another location"}. Check the --url option / FILECAFE_URL (e.g. use https:// instead of http://).`, response.status);
105
- }
106
- const text = await response.text();
101
+ 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);
107
102
  let json = null;
108
103
  if (text) try {
109
104
  json = JSON.parse(text);
@@ -245,7 +240,7 @@ async function resolveSettings(environment, urlOption) {
245
240
  };
246
241
  }
247
242
  // src/version.ts
248
- const VERSION = "0.1.0";
243
+ const VERSION = "0.2.0";
249
244
  // src/context.ts
250
245
  /** Open a URL in the default browser without ever throwing. */
251
246
  function openBrowser(url, platform = process.platform) {
@@ -283,7 +278,8 @@ function createDefaultContext() {
283
278
  platform: process.platform,
284
279
  homedir: homedir(),
285
280
  fetch: (input, init) => fetch(input, init),
286
- sleep: (ms) => setTimeout$1(ms),
281
+ sleep: (ms) => setTimeout(ms),
282
+ now: () => Date.now(),
287
283
  stdout: process.stdout,
288
284
  stderr: process.stderr,
289
285
  stdin: process.stdin,
@@ -298,116 +294,6 @@ var CliError = class extends Error {
298
294
  this.name = "CliError";
299
295
  }
300
296
  };
301
- // src/login-server.ts
302
- const LOGIN_TIMEOUT_MS = 3e5;
303
- function generateState() {
304
- return randomBytes(16).toString("hex");
305
- }
306
- function statesMatch(received, expected) {
307
- if (received === null) return false;
308
- const a = Buffer.from(received, "utf8");
309
- const b = Buffer.from(expected, "utf8");
310
- return a.length === b.length && timingSafeEqual(a, b);
311
- }
312
- function page(title, message) {
313
- return `<!doctype html>
314
- <html lang="en">
315
- <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title>
316
- <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>
317
- </head>
318
- <body><main><h1>${title}</h1><p>${message}</p></main></body>
319
- </html>
320
- `;
321
- }
322
- const SUCCESS_PAGE = page("You're logged in to file.cafe.", "You can close this tab and return to your terminal.");
323
- const DENIED_PAGE = page("Login cancelled.", "The file.cafe CLI was not authorized. You can close this tab.");
324
- const FAILED_PAGE = page("Login failed.", "Something went wrong. Return to your terminal and run \"filecafe login\" again.");
325
- const INVALID_PAGE = page("Invalid login request.", "This link does not match the login started in your terminal. Run \"filecafe login\" again.");
326
- /**
327
- * Decide how to answer a request to the local callback server. Only
328
- * `GET /callback` with the expected `state` concludes the login; anything
329
- * else is rejected and the server keeps waiting.
330
- */
331
- function handleCallbackRequest(method, rawUrl, expectedState) {
332
- const url = new URL(rawUrl ?? "/", "http://127.0.0.1");
333
- if (method !== "GET" || url.pathname !== "/callback") return {
334
- status: 404,
335
- body: page("Not found.", "Nothing to see here.")
336
- };
337
- if (!statesMatch(url.searchParams.get("state"), expectedState)) return {
338
- status: 400,
339
- body: INVALID_PAGE
340
- };
341
- const error = url.searchParams.get("error");
342
- if (error) return {
343
- status: 200,
344
- body: error === "access_denied" ? DENIED_PAGE : FAILED_PAGE,
345
- result: { error }
346
- };
347
- const token = url.searchParams.get("token");
348
- if (!token) return {
349
- status: 400,
350
- body: FAILED_PAGE
351
- };
352
- return {
353
- status: 200,
354
- body: SUCCESS_PAGE,
355
- result: { token }
356
- };
357
- }
358
- /** Listen on a random loopback port for the browser redirect. */
359
- function startCallbackServer(state, timeoutMs = LOGIN_TIMEOUT_MS) {
360
- let settle = () => {};
361
- let fail = () => {};
362
- let settled = false;
363
- const result = new Promise((resolve, reject) => {
364
- settle = resolve;
365
- fail = reject;
366
- });
367
- const server = createServer((request, response) => {
368
- const outcome = handleCallbackRequest(request.method, request.url, state);
369
- response.writeHead(outcome.status, {
370
- "Content-Type": "text/html; charset=utf-8",
371
- "Cache-Control": "no-store",
372
- "Referrer-Policy": "no-referrer",
373
- Connection: "close"
374
- });
375
- response.end(outcome.body);
376
- if (outcome.result && !settled) {
377
- const loginResult = outcome.result;
378
- response.on("finish", () => finish(() => settle(loginResult)));
379
- }
380
- });
381
- let timer;
382
- const close = () => {
383
- clearTimeout(timer);
384
- server.close();
385
- server.closeAllConnections();
386
- };
387
- const finish = (callback) => {
388
- if (settled) return;
389
- settled = true;
390
- close();
391
- callback();
392
- };
393
- return new Promise((resolve, reject) => {
394
- server.once("error", reject);
395
- server.listen(0, "127.0.0.1", () => {
396
- const address = server.address();
397
- if (!address || typeof address === "string") {
398
- close();
399
- reject(/* @__PURE__ */ new Error("Could not start the local login server."));
400
- return;
401
- }
402
- 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);
403
- resolve({
404
- port: address.port,
405
- result,
406
- close: () => finish(() => fail(/* @__PURE__ */ new Error("Login cancelled.")))
407
- });
408
- });
409
- });
410
- }
411
297
  // src/session.ts
412
298
  const NOT_LOGGED_IN = "Not logged in. Run \"filecafe login\" or set FILECAFE_TOKEN.";
413
299
  function clientFor(context, baseUrl, token, onNotice) {
@@ -447,19 +333,48 @@ async function readAll(input) {
447
333
  for await (const chunk of input) text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
448
334
  return text;
449
335
  }
450
- function authorizeUrl(baseUrl, port, state, name) {
451
- return `${baseUrl}/cli/authorize?port=${port}&state=${state}&name=${encodeURIComponent(name)}`;
336
+ const EXPIRED_MESSAGE = "The login code expired before it was approved. Run \"filecafe login\" again.";
337
+ function isStartedLogin(value) {
338
+ if (!value || typeof value !== "object") return false;
339
+ const login = value;
340
+ return typeof login.device_code === "string" && typeof login.user_code === "string" && typeof login.verification_uri === "string" && typeof login.verification_uri_complete === "string" && typeof login.expires_in === "number" && typeof login.interval === "number";
341
+ }
342
+ /**
343
+ * Ask where the login stands, treating a dropped connection or server hiccup
344
+ * as "still pending" so one bad poll does not end the login.
345
+ */
346
+ async function pollLogin(client, deviceCode) {
347
+ try {
348
+ return await client.request("POST", "/api/v1/cli/logins/token", { device_code: deviceCode });
349
+ } catch (error) {
350
+ if (error instanceof ApiError && (error.status === null || error.status >= 500)) return { status: "pending" };
351
+ throw error;
352
+ }
452
353
  }
453
- async function tokenFromBrowser(context, baseUrl, timeoutMs) {
454
- const state = generateState();
455
- const server = await startCallbackServer(state, timeoutMs);
456
- const url = authorizeUrl(baseUrl, server.port, state, hostname());
457
- context.stderr.write(`Opening your browser to log in to ${baseUrl}.\n`);
458
- context.stderr.write(`If it does not open, visit this URL on this machine:\n\n ${url}\n\nWaiting for approval...\n`);
459
- context.openBrowser(url);
460
- const result = await server.result;
461
- if ("error" in result) throw new CliError(result.error === "access_denied" ? "Login was cancelled in the browser." : `Login failed in the browser (${result.error}).`);
462
- return result.token;
354
+ /**
355
+ * Start a login on file.cafe, show its code, and poll until it is approved in
356
+ * the browser. The token only exists once this collects it, and nothing
357
+ * listens on a local port, so it works over SSH too.
358
+ */
359
+ async function tokenFromBrowser(context, baseUrl) {
360
+ const client = clientFor(context, baseUrl, void 0, (message) => context.stderr.write(`${message}\n`));
361
+ const login = await client.request("POST", "/api/v1/cli/logins", { name: hostname() });
362
+ if (!isStartedLogin(login)) throw new CliError(`Unexpected response from ${baseUrl} when starting the login. Check the --url option / FILECAFE_URL.`);
363
+ context.stderr.write(`Your one-time code: ${login.user_code}\n\nOpening your browser to approve this login. Check that the code there matches.\nIf it does not open, visit ${login.verification_uri} and enter the code.\n\nWaiting for approval...
364
+ `);
365
+ context.openBrowser(login.verification_uri_complete);
366
+ const intervalMs = Math.max(login.interval, 1) * 1e3;
367
+ const deadline = context.now() + login.expires_in * 1e3;
368
+ while (context.now() < deadline) {
369
+ await context.sleep(Math.min(intervalMs, deadline - context.now()));
370
+ const result = await pollLogin(client, login.device_code);
371
+ switch (result.status) {
372
+ case "approved": return result.token;
373
+ case "denied": throw new CliError("Login was cancelled in the browser.");
374
+ case "expired": throw new CliError(EXPIRED_MESSAGE);
375
+ }
376
+ }
377
+ throw new CliError(EXPIRED_MESSAGE);
463
378
  }
464
379
  async function loginCommand(options, globals, context) {
465
380
  if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
@@ -474,7 +389,7 @@ async function loginCommand(options, globals, context) {
474
389
  else if (options.withToken) {
475
390
  if (context.stdin.isTTY) throw new CliError("--with-token reads the token from standard input, e.g.: echo \"$TOKEN\" | filecafe login --with-token");
476
391
  token = (await readAll(context.stdin)).trim();
477
- } else token = await tokenFromBrowser(context, baseUrl, options.timeoutMs ?? 3e5);
392
+ } else token = await tokenFromBrowser(context, baseUrl);
478
393
  if (!token || /\s/.test(token)) throw new CliError("The token is empty or malformed.");
479
394
  let me;
480
395
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "filecafe",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Upload files to file.cafe from the command line. Built for AI coding agents, humans, and CI.",
5
5
  "keywords": [
6
6
  "file.cafe",
@@ -34,5 +34,9 @@
34
34
  "@types/node": "^24.19.2",
35
35
  "tsdown": "^0.23.1",
36
36
  "typescript": "^7.0.2"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/filecafe/cli.git"
37
41
  }
38
42
  }