filecafe 0.1.1 → 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.
- package/README.md +1 -1
- package/dist/cli.js +47 -129
- package/package.json +1 -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
|
|
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,7 +75,7 @@ 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";
|
|
@@ -242,7 +240,7 @@ async function resolveSettings(environment, urlOption) {
|
|
|
242
240
|
};
|
|
243
241
|
}
|
|
244
242
|
// src/version.ts
|
|
245
|
-
const VERSION = "0.
|
|
243
|
+
const VERSION = "0.2.0";
|
|
246
244
|
// src/context.ts
|
|
247
245
|
/** Open a URL in the default browser without ever throwing. */
|
|
248
246
|
function openBrowser(url, platform = process.platform) {
|
|
@@ -280,7 +278,8 @@ function createDefaultContext() {
|
|
|
280
278
|
platform: process.platform,
|
|
281
279
|
homedir: homedir(),
|
|
282
280
|
fetch: (input, init) => fetch(input, init),
|
|
283
|
-
sleep: (ms) => setTimeout
|
|
281
|
+
sleep: (ms) => setTimeout(ms),
|
|
282
|
+
now: () => Date.now(),
|
|
284
283
|
stdout: process.stdout,
|
|
285
284
|
stderr: process.stderr,
|
|
286
285
|
stdin: process.stdin,
|
|
@@ -295,116 +294,6 @@ var CliError = class extends Error {
|
|
|
295
294
|
this.name = "CliError";
|
|
296
295
|
}
|
|
297
296
|
};
|
|
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
297
|
// src/session.ts
|
|
409
298
|
const NOT_LOGGED_IN = "Not logged in. Run \"filecafe login\" or set FILECAFE_TOKEN.";
|
|
410
299
|
function clientFor(context, baseUrl, token, onNotice) {
|
|
@@ -444,19 +333,48 @@ async function readAll(input) {
|
|
|
444
333
|
for await (const chunk of input) text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
445
334
|
return text;
|
|
446
335
|
}
|
|
447
|
-
|
|
448
|
-
|
|
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
|
+
}
|
|
449
353
|
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
context.
|
|
457
|
-
const
|
|
458
|
-
if (
|
|
459
|
-
|
|
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);
|
|
460
378
|
}
|
|
461
379
|
async function loginCommand(options, globals, context) {
|
|
462
380
|
if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
|
|
@@ -471,7 +389,7 @@ async function loginCommand(options, globals, context) {
|
|
|
471
389
|
else if (options.withToken) {
|
|
472
390
|
if (context.stdin.isTTY) throw new CliError("--with-token reads the token from standard input, e.g.: echo \"$TOKEN\" | filecafe login --with-token");
|
|
473
391
|
token = (await readAll(context.stdin)).trim();
|
|
474
|
-
} else token = await tokenFromBrowser(context, baseUrl
|
|
392
|
+
} else token = await tokenFromBrowser(context, baseUrl);
|
|
475
393
|
if (!token || /\s/.test(token)) throw new CliError("The token is empty or malformed.");
|
|
476
394
|
let me;
|
|
477
395
|
try {
|