@rebasepro/cli 0.29.3 → 0.30.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.
@@ -268,16 +268,114 @@ function readMfaRequired(error) {
268
268
  };
269
269
  }
270
270
  /**
271
+ * The control plane's `/auth/config`, or null when it cannot be read. Read
272
+ * once per login: it says both whether codes are mailed and whether device
273
+ * sign-in is offered.
274
+ */
275
+ async function readAuthConfig(auth) {
276
+ try {
277
+ return await auth.getAuthConfig();
278
+ } catch {
279
+ return null;
280
+ }
281
+ }
282
+ /**
271
283
  * Whether the control plane mails sign-in codes, as its `/auth/config` says.
272
284
  * `false` when it cannot be asked: an older control plane has no such door,
273
285
  * and offering one that 404s is worse than not offering it.
274
286
  */
275
- async function offersSignInCodes(auth) {
287
+ function offersSignInCodes(config) {
288
+ return config?.emailOtp === true;
289
+ }
290
+ /** Whether the control plane signs a terminal in through a browser, as its `/auth/config` says. */
291
+ function offersBrowserSignIn(config) {
292
+ return config?.deviceLogin === true;
293
+ }
294
+ /** What the browser sign-in does outside this process. An object so tests can replace it. */
295
+ var BROWSER_SIGN_IN_IO = {
296
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
297
+ open: (url) => openUrl(url, "Opening")
298
+ };
299
+ /** What the approval page calls this terminal. */
300
+ function browserSignInClientName() {
301
+ let host = "";
276
302
  try {
277
- return (await auth.getAuthConfig()).emailOtp === true;
278
- } catch {
279
- return false;
303
+ host = os.hostname().replace(/\.local$/, "");
304
+ } catch {}
305
+ return host ? `Rebase CLI on ${host}` : "Rebase CLI";
306
+ }
307
+ /** How long to wait after a poll that could not get an answer, at most. */
308
+ var MAX_RETRY_INTERVAL_SECONDS = 30;
309
+ /**
310
+ * Sign in through a browser: ask for a pending sign-in, show its link and
311
+ * code, open the browser when there is a person at a terminal to look at it,
312
+ * and poll until it is approved, denied or expired.
313
+ *
314
+ * Without a terminal — piped, or `--json` — the link and code still go to
315
+ * stderr and the polling still happens: whoever runs this (an agent, a
316
+ * script with a person nearby) has what to open and is told what it is
317
+ * waiting for.
318
+ */
319
+ async function signInWithBrowser(auth, options) {
320
+ let started;
321
+ try {
322
+ started = await auth.startDeviceLogin({ clientName: browserSignInClientName() });
323
+ } catch (e) {
324
+ if (errorStatus(e) === 404) fail("This control plane does not offer signing in through a browser.", "Run `rebase cloud login --email <address>` to sign in with your password or an emailed code.", "device_login_unavailable");
325
+ throw e;
326
+ }
327
+ const minutes = Math.max(1, Math.round(started.expiresIn / 60));
328
+ if (isJsonMode()) {
329
+ process.stderr.write(`To sign in, open ${started.verificationUriComplete}\n`);
330
+ process.stderr.write(` and check that it shows the code ${started.userCode}.\n`);
331
+ process.stderr.write(`Waiting for the sign-in to be approved in the browser (expires in ${minutes} minutes)...\n`);
332
+ } else {
333
+ noteBlank();
334
+ note(`Your code: ${chalk.bold(started.userCode)}`);
335
+ if (options.openBrowser && atTerminal()) {
336
+ BROWSER_SIGN_IN_IO.open(started.verificationUriComplete);
337
+ note(chalk.gray("If the browser did not open, open the link above yourself."));
338
+ } else {
339
+ noteBlank();
340
+ note(`Open ${chalk.cyan(started.verificationUriComplete)}`);
341
+ }
342
+ note(chalk.gray("Check that the page shows the same code, then approve the sign-in there."));
343
+ noteBlank();
344
+ note(chalk.gray(`Waiting for approval in the browser (expires in ${minutes} minutes, Ctrl-C to cancel)…`));
280
345
  }
346
+ const deadline = Date.now() + started.expiresIn * 1e3;
347
+ let interval = started.interval;
348
+ let warnedUnreachable = false;
349
+ while (Date.now() < deadline) {
350
+ await BROWSER_SIGN_IN_IO.sleep(interval * 1e3);
351
+ let result;
352
+ try {
353
+ result = await auth.pollDeviceLogin(started.deviceCode);
354
+ } catch (e) {
355
+ const status = errorStatus(e);
356
+ if (!(typeof status !== "number" || status === 429 || status >= 500)) throw e;
357
+ if (!warnedUnreachable) {
358
+ warn("Could not reach the control plane to check on the sign-in. Still waiting.");
359
+ warnedUnreachable = true;
360
+ }
361
+ interval = Math.min(interval + 5, MAX_RETRY_INTERVAL_SECONDS);
362
+ continue;
363
+ }
364
+ switch (result.status) {
365
+ case "approved": return {
366
+ user: result.user,
367
+ accessToken: result.accessToken,
368
+ refreshToken: result.refreshToken
369
+ };
370
+ case "pending":
371
+ case "slow_down":
372
+ interval = result.interval;
373
+ break;
374
+ case "denied": return fail("The sign-in was denied in the browser.", "Nothing was signed in. To sign in, run `rebase cloud login` again.", "access_denied");
375
+ case "expired": return fail("The sign-in link expired before it was approved.", "Run `rebase cloud login` again for a new link.", "expired_token");
376
+ }
377
+ }
378
+ fail("The sign-in link expired before it was approved.", "Run `rebase cloud login` again for a new link.", "expired_token");
281
379
  }
282
380
  /** Ask "password or code?" at a terminal. */
283
381
  async function askSignInMethod() {
@@ -645,6 +743,8 @@ var LOGIN_FLAGS = {
645
743
  "--email": String,
646
744
  "--password": String,
647
745
  "--code": Boolean,
746
+ "--web": Boolean,
747
+ "--no-browser": Boolean,
648
748
  "-e": "--email"
649
749
  };
650
750
  /**
@@ -687,37 +787,43 @@ async function loginCommand(rawArgs) {
687
787
  note(`Signing in to ${chalk.cyan(url)}`);
688
788
  noteBlank();
689
789
  if (args["--code"] && passwordOnTheCommandLine(args)) fail("--code and --password are two ways to sign in. Pass one of them.", void 0, "usage");
790
+ if (args["--web"] && (args["--code"] || args["--email"] || passwordOnTheCommandLine(args))) fail("--web signs in through the browser, with no email, password or code. Pass it on its own.", void 0, "usage");
690
791
  if (passwordOnTheCommandLine(args)) warn("--password puts your password in your shell history and in the process table.", `Prefer the prompt, or pass it as ${PASSWORD_ENV} from a secret store.`);
691
792
  const envEmail = (process.env["REBASE_CLOUD_EMAIL"] ?? "").trim();
692
793
  const envPassword = process.env["REBASE_CLOUD_PASSWORD"] ?? "";
693
- let method = args["--code"] ? "code" : args["--password"] || envPassword ? "password" : void 0;
794
+ let method = args["--web"] ? "browser" : args["--code"] ? "code" : args["--password"] || envPassword ? "password" : void 0;
694
795
  if (method === "code") requireTerminalForCode();
695
- let email = (args["--email"] || envEmail).trim();
696
- if (!email || method === void 0) requireInteractive("credentials", `--email and --password, or ${EMAIL_ENV} and ${PASSWORD_ENV}`);
697
- if (!email) {
698
- const answers = await inquirer.prompt([{
699
- type: "input",
700
- name: "email",
701
- message: "Email:"
702
- }]);
703
- email = String(answers.email ?? "").trim();
704
- }
705
- if (!email) fail("An email is required.", void 0, "input_required");
706
796
  const client = createCloudClient(url);
707
- if (method === void 0) method = await offersSignInCodes(client.auth) ? await askSignInMethod() : "password";
797
+ let authConfig;
798
+ const config = async () => authConfig === void 0 ? authConfig = await readAuthConfig(client.auth) : authConfig;
799
+ if (method === void 0 && !args["--email"] && offersBrowserSignIn(await config())) method = "browser";
800
+ let email = (args["--email"] || envEmail).trim();
708
801
  let password = args["--password"] || envPassword;
709
- if (method === "password" && !password) {
710
- const answers = await inquirer.prompt([{
711
- type: "password",
712
- name: "password",
713
- message: "Password:",
714
- mask: "•"
715
- }]);
716
- password = String(answers.password ?? "");
802
+ if (method !== "browser") {
803
+ if (!email || method === void 0) requireInteractive("credentials", `--email and --password, or ${EMAIL_ENV} and ${PASSWORD_ENV}`);
804
+ if (!email) {
805
+ const answers = await inquirer.prompt([{
806
+ type: "input",
807
+ name: "email",
808
+ message: "Email:"
809
+ }]);
810
+ email = String(answers.email ?? "").trim();
811
+ }
812
+ if (!email) fail("An email is required.", void 0, "input_required");
813
+ if (method === void 0) method = offersSignInCodes(await config()) ? await askSignInMethod() : "password";
814
+ if (method === "password" && !password) {
815
+ const answers = await inquirer.prompt([{
816
+ type: "password",
817
+ name: "password",
818
+ message: "Password:",
819
+ mask: "•"
820
+ }]);
821
+ password = String(answers.password ?? "");
822
+ }
823
+ if (method === "password" && !password) fail("Email and password are required.");
717
824
  }
718
- if (method === "password" && !password) fail("Email and password are required.");
719
825
  try {
720
- const { user } = await withSecondFactor(client.auth, () => method === "code" ? signInWithCode(client.auth, email) : client.auth.signInWithEmail(email, password));
826
+ const { user } = method === "browser" ? await signInWithBrowser(client.auth, { openBrowser: !args["--no-browser"] }) : await withSecondFactor(client.auth, () => method === "code" ? signInWithCode(client.auth, email) : client.auth.signInWithEmail(email, password));
721
827
  setCurrentContext(url);
722
828
  try {
723
829
  const orgs = await client.data.collection("organizations").find({ limit: 2 });
@@ -14258,23 +14364,29 @@ var ACTION_HELP = {
14258
14364
  },
14259
14365
  login: {
14260
14366
  command: "cloud login",
14261
- usage: "cloud login [--email <address>] [--password <password> | --code]",
14262
- summary: "Sign in to the control plane and write the session to ~/.rebase/credentials.json. Prompts for whatever is missing when attached to a terminal, and refuses rather than hangs when it is not.",
14367
+ usage: "cloud login [--web] [--no-browser] | [--email <address>] [--password <password> | --code]",
14368
+ summary: "Sign in to the control plane and write the session to ~/.rebase/credentials.json. With no flags, signs in through the browser: prints a link and a short code, opens the browser, and waits while you approve the sign-in in the console, where you are signed in already or sign in with any method it offers (password, Google, GitHub, LinkedIn). Nothing is typed into the terminal.",
14263
14369
  flags: [
14264
- ["--email, -e <address>", "The account's email. Prompted when omitted, or REBASE_CLOUD_EMAIL"],
14370
+ ["--web", "Sign in through the browser. The default when the control plane offers it and no --email, --password or --code is given"],
14371
+ ["--no-browser", "Print the link instead of opening the browser, for a terminal on another machine (over SSH)"],
14372
+ ["--email, -e <address>", "Sign in with this account's email instead of the browser: its password, or an emailed code. Or REBASE_CLOUD_EMAIL with REBASE_CLOUD_PASSWORD"],
14265
14373
  ["--password <password>", "Discouraged: a password written here is recorded in your shell history and visible in the process table. Prefer the prompt, or REBASE_CLOUD_PASSWORD"],
14266
14374
  ["--code", "Sign in with a 6-digit code emailed to you instead of a password: the way in for accounts made with Google, GitHub or LinkedIn. Needs a terminal"]
14267
14375
  ],
14268
14376
  examples: [
14269
14377
  "rebase cloud login",
14378
+ "rebase cloud login --no-browser",
14270
14379
  "rebase cloud login --email me@example.com",
14271
14380
  "rebase cloud login --code --email me@example.com",
14272
14381
  "rebase cloud login --url https://cloud.example.com"
14273
14382
  ],
14274
14383
  notes: [
14275
- "At a terminal with no password given, login asks whether to use your password or an emailed code, when the control plane sends codes.",
14276
- "With two-factor authentication on, login then asks for the code from your authenticator app (or a recovery code), whichever way you signed in.",
14277
- "Without a terminal, a code or a second factor cannot be typed: create an access token in the console (Settings → Access tokens) and set REBASE_TOKEN instead.",
14384
+ "Check that the code the browser shows is the one the terminal printed before you approve: approving gives this terminal a session for the account signed in to that browser.",
14385
+ "The link expires after 10 minutes and works once. Denying it in the browser ends the login here.",
14386
+ "Without a terminal, or with --json, the link and code are printed on stderr and login keeps waiting for the approval, so an agent or script can hand the link to a person.",
14387
+ "With two-factor authentication on, approve from a console session that used it. With --email, login asks for the code from your authenticator app (or a recovery code) instead.",
14388
+ "A control plane that does not offer browser sign-in gets the email prompts, as before: at a terminal with no password given, login asks whether to use your password or an emailed code, when the control plane sends codes.",
14389
+ "Without a terminal, an email code or a second factor cannot be typed: create an access token in the console (Settings → Access tokens) and set REBASE_TOKEN instead.",
14278
14390
  "--password warns, once, before the request: by the time a login succeeds the password is already in the history file.",
14279
14391
  "CI should not log in at all: `rebase cloud tokens create` mints a token for REBASE_TOKEN. Where a login is still wanted, REBASE_CLOUD_EMAIL and REBASE_CLOUD_PASSWORD are how a secret store hands the credentials over without them appearing on a command line.",
14280
14392
  "In a directory whose .rebase/cloud.json names a control plane you have not signed in to before, login names it and asks first, and refuses without a terminal: a cloned repository does not choose where your password goes. Pass --url <that host> to sign in there on purpose."
@@ -15179,4 +15291,4 @@ function printCloudHelp() {
15179
15291
  //#endregion
15180
15292
  export { CLOUD_GROUP_NAMES, GROUP_ALIASES, cloudCommand };
15181
15293
 
15182
- //# sourceMappingURL=cloud-Cj5ey3l_.js.map
15294
+ //# sourceMappingURL=cloud-DtADfWwn.js.map