@nlxai/cli 1.2.2-alpha.8 → 1.2.3-alpha.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.
@@ -4,15 +4,28 @@ import open from "open";
4
4
  import * as os from "os";
5
5
  import * as path from "path";
6
6
  import { consola } from "consola";
7
- import keytar from "keytar";
7
+ import { singleton } from "../../utils/index.js";
8
8
  export const ACCOUNTS_PATH = path.join(os.homedir(), ".nlx-cli-auth.json");
9
+ let _keytar;
10
+ export async function getKeytar() {
11
+ if (_keytar)
12
+ return _keytar;
13
+ _keytar = (await import("keytar")).default;
14
+ return _keytar;
15
+ }
9
16
  async function saveTokens(account, tokenData) {
10
- await keytar.setPassword("nlx-cli", account, JSON.stringify(tokenData));
17
+ if (!process.env.NLX_ACCESS_TOKEN) {
18
+ const keytar = await getKeytar();
19
+ await keytar.setPassword("nlx-cli", account, JSON.stringify(tokenData));
20
+ }
21
+ else {
22
+ process.env.NLX_ACCESS_TOKEN = btoa(JSON.stringify([account, tokenData]));
23
+ }
11
24
  }
12
25
  async function loadTokens() {
13
26
  if (process.env.NLX_ACCESS_TOKEN) {
14
27
  try {
15
- console.log("Using access token from NLX_ACCESS_TOKEN environment variable");
28
+ consola.info("Using access token from NLX_ACCESS_TOKEN environment variable");
16
29
  return JSON.parse(atob(process.env.NLX_ACCESS_TOKEN));
17
30
  }
18
31
  catch (error) {
@@ -23,6 +36,7 @@ async function loadTokens() {
23
36
  const data = fs.readFileSync(ACCOUNTS_PATH, "utf8");
24
37
  const accounts = JSON.parse(data);
25
38
  if (accounts.currentAccount) {
39
+ const keytar = await getKeytar();
26
40
  const res = await keytar.getPassword("nlx-cli", accounts.currentAccount);
27
41
  if (res)
28
42
  return [accounts.currentAccount, JSON.parse(res)];
@@ -33,7 +47,7 @@ async function loadTokens() {
33
47
  throw new Error("Failed to load tokens");
34
48
  }
35
49
  }
36
- async function refreshTokenIfNeeded() {
50
+ const refreshTokenIfNeeded = singleton(async function () {
37
51
  let account, tokens;
38
52
  try {
39
53
  [account, tokens] = await loadTokens();
@@ -71,7 +85,7 @@ async function refreshTokenIfNeeded() {
71
85
  return newTokens.access_token;
72
86
  }
73
87
  return null;
74
- }
88
+ });
75
89
  const AUTH0_DOMAIN = process.env.AUTH0_DOMAIN || "nlxdev.us.auth0.com"; // e.g. 'dev-xxxxxx.us.auth0.com'
76
90
  const CLIENT_ID = process.env.AUTH0_CLIENT_ID || "A0qluq7wJQjFjMLle9pvrWWaVHM1QHE3";
77
91
  const AUDIENCE = process.env.AUTH0_AUDIENCE || "https://nlxdev.us.auth0.com/api/v2/";
@@ -143,11 +157,10 @@ export const loginCommand = new Command("login")
143
157
  tokenData.obtained_at = Math.floor(Date.now() / 1000);
144
158
  await saveTokens(userData.email, tokenData);
145
159
  if (opts.printToken) {
146
- console.log("Access token", btoa(JSON.stringify([userData.email, tokenData])));
160
+ consola.success("Access token", btoa(JSON.stringify([userData.email, tokenData])));
147
161
  }
148
162
  consola.success("Login successful! Access token stored securely.");
149
163
  });
150
- // Example usage: get a valid access token
151
164
  export async function ensureToken() {
152
165
  const accessToken = await refreshTokenIfNeeded();
153
166
  if (!accessToken) {
@@ -1,7 +1,6 @@
1
1
  import { Command } from "commander";
2
2
  import { consola } from "consola";
3
- import { ACCOUNTS_PATH } from "./login.js";
4
- import keytar from "keytar";
3
+ import { ACCOUNTS_PATH, getKeytar } from "./login.js";
5
4
  import * as fs from "fs";
6
5
  export const logoutCommand = new Command("logout")
7
6
  .description("Clear stored authentication tokens")
@@ -13,6 +12,7 @@ export const logoutCommand = new Command("logout")
13
12
  accounts = JSON.parse(data);
14
13
  }
15
14
  if (accounts.currentAccount) {
15
+ const keytar = await getKeytar();
16
16
  await keytar.deletePassword("nlx-cli", accounts.currentAccount);
17
17
  accounts.accounts = accounts.accounts.filter((acc) => acc !== accounts.currentAccount);
18
18
  if (accounts.accounts.length > 0) {
@@ -4,142 +4,150 @@ import open from "open";
4
4
  import * as os from "os";
5
5
  import * as path from "path";
6
6
  import { consola } from "consola";
7
- import keytar from "keytar";
8
7
  const ACCOUNTS_PATH = path.join(os.homedir(), ".nlx-cli-auth.json");
9
8
  async function saveTokens(account, tokenData) {
10
- await keytar.setPassword("nlx-cli", account, JSON.stringify(tokenData));
9
+ await keytar.setPassword("nlx-cli", account, JSON.stringify(tokenData));
11
10
  }
12
11
  async function loadTokens() {
13
- try {
14
- const data = fs.readFileSync(ACCOUNTS_PATH, "utf8");
15
- const accounts = JSON.parse(data);
16
- if (accounts.currentAccount) {
17
- const res = await keytar.getPassword("nlx-cli", accounts.currentAccount);
18
- if (res)
19
- return [accounts.currentAccount, JSON.parse(res)];
20
- }
21
- throw new Error("No tokens found for current account");
22
- }
23
- catch {
24
- throw new Error("Failed to load tokens");
12
+ try {
13
+ const data = fs.readFileSync(ACCOUNTS_PATH, "utf8");
14
+ const accounts = JSON.parse(data);
15
+ if (accounts.currentAccount) {
16
+ const res = await keytar.getPassword("nlx-cli", accounts.currentAccount);
17
+ if (res) return [accounts.currentAccount, JSON.parse(res)];
25
18
  }
19
+ throw new Error("No tokens found for current account");
20
+ } catch {
21
+ throw new Error("Failed to load tokens");
22
+ }
26
23
  }
27
24
  async function refreshTokenIfNeeded() {
28
- let account, tokens;
29
- try {
30
- [account, tokens] = await loadTokens();
31
- }
32
- catch (error) {
33
- consola.error("Error loading tokens");
34
- return null;
35
- }
36
- if (!tokens || !tokens.refresh_token)
37
- return null;
38
- // Check expiry
39
- const now = Math.floor(Date.now() / 1000);
40
- if (tokens.expires_in &&
41
- tokens.obtained_at &&
42
- now < tokens.obtained_at + tokens.expires_in - 60) {
43
- consola.debug("Access token is still valid.");
44
- return tokens.access_token;
45
- }
46
- consola.debug("Access token is expired or invalid. Refreshing...");
47
- // Refresh
48
- const res = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
49
- method: "POST",
50
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
51
- body: new URLSearchParams({
52
- grant_type: "refresh_token",
53
- client_id: CLIENT_ID,
54
- refresh_token: tokens.refresh_token,
55
- }),
56
- });
57
- const newTokens = await res.json();
58
- if (newTokens.access_token) {
59
- newTokens.refresh_token = newTokens.refresh_token || tokens.refresh_token;
60
- newTokens.obtained_at = now;
61
- await saveTokens(account, newTokens);
62
- return newTokens.access_token;
63
- }
25
+ let account, tokens;
26
+ try {
27
+ [account, tokens] = await loadTokens();
28
+ } catch (error) {
29
+ consola.error("Error loading tokens");
64
30
  return null;
31
+ }
32
+ if (!tokens || !tokens.refresh_token) return null;
33
+ // Check expiry
34
+ const now = Math.floor(Date.now() / 1000);
35
+ if (
36
+ tokens.expires_in &&
37
+ tokens.obtained_at &&
38
+ now < tokens.obtained_at + tokens.expires_in - 60
39
+ ) {
40
+ consola.debug("Access token is still valid.");
41
+ return tokens.access_token;
42
+ }
43
+ consola.debug("Access token is expired or invalid. Refreshing...");
44
+ // Refresh
45
+ const res = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
46
+ method: "POST",
47
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
48
+ body: new URLSearchParams({
49
+ grant_type: "refresh_token",
50
+ client_id: CLIENT_ID,
51
+ refresh_token: tokens.refresh_token,
52
+ }),
53
+ });
54
+ const newTokens = await res.json();
55
+ if (newTokens.access_token) {
56
+ newTokens.refresh_token = newTokens.refresh_token || tokens.refresh_token;
57
+ newTokens.obtained_at = now;
58
+ await saveTokens(account, newTokens);
59
+ return newTokens.access_token;
60
+ }
61
+ return null;
65
62
  }
66
63
  const AUTH0_DOMAIN = process.env.AUTH0_DOMAIN || "nlxdev.us.auth0.com"; // e.g. 'dev-xxxxxx.us.auth0.com'
67
- const CLIENT_ID = process.env.AUTH0_CLIENT_ID || "A0qluq7wJQjFjMLle9pvrWWaVHM1QHE3";
68
- const AUDIENCE = process.env.AUTH0_AUDIENCE || "https://nlxdev.us.auth0.com/api/v2/";
64
+ const CLIENT_ID =
65
+ process.env.AUTH0_CLIENT_ID || "A0qluq7wJQjFjMLle9pvrWWaVHM1QHE3";
66
+ const AUDIENCE =
67
+ process.env.AUTH0_AUDIENCE || "https://nlxdev.us.auth0.com/api/v2/";
69
68
  export const loginCommand = new Command("login")
70
- .description("Authenticate with NLX")
71
- .action(async () => {
69
+ .description("Authenticate with NLX")
70
+ .action(async () => {
72
71
  // Step 1: Start device flow
73
- const deviceCodeRes = await fetch(`https://${AUTH0_DOMAIN}/oauth/device/code`, {
72
+ const deviceCodeRes = await fetch(
73
+ `https://${AUTH0_DOMAIN}/oauth/device/code`,
74
+ {
74
75
  method: "POST",
75
76
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
76
77
  body: new URLSearchParams({
77
- client_id: CLIENT_ID,
78
- scope: "openid profile email offline_access",
79
- audience: AUDIENCE,
78
+ client_id: CLIENT_ID,
79
+ scope: "openid profile email offline_access",
80
+ audience: AUDIENCE,
80
81
  }),
81
- });
82
+ },
83
+ );
82
84
  const deviceCodeData = await deviceCodeRes.json();
83
85
  open(deviceCodeData.verification_uri_complete);
84
- consola.box(`Please visit ${deviceCodeData.verification_uri_complete} and enter code: ${deviceCodeData.user_code}`);
86
+ consola.box(
87
+ `Please visit ${deviceCodeData.verification_uri_complete} and enter code: ${deviceCodeData.user_code}`,
88
+ );
85
89
  // Step 2: Poll for token
86
90
  let tokenData;
87
91
  while (!tokenData) {
88
- await new Promise((r) => setTimeout(r, deviceCodeData.interval * 1000));
89
- const tokenRes = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
90
- method: "POST",
91
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
92
- body: new URLSearchParams({
93
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
94
- device_code: deviceCodeData.device_code,
95
- client_id: CLIENT_ID,
96
- }),
97
- });
98
- const resData = await tokenRes.json();
99
- if (resData.access_token) {
100
- tokenData = resData;
101
- }
102
- else if (resData.error !== "authorization_pending") {
103
- consola.error("Error:", resData.error_description || resData.error);
104
- return;
105
- }
92
+ await new Promise((r) => setTimeout(r, deviceCodeData.interval * 1000));
93
+ const tokenRes = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
94
+ method: "POST",
95
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
96
+ body: new URLSearchParams({
97
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
98
+ device_code: deviceCodeData.device_code,
99
+ client_id: CLIENT_ID,
100
+ }),
101
+ });
102
+ const resData = await tokenRes.json();
103
+ if (resData.access_token) {
104
+ tokenData = resData;
105
+ } else if (resData.error !== "authorization_pending") {
106
+ consola.error("Error:", resData.error_description || resData.error);
107
+ return;
108
+ }
106
109
  }
107
110
  // Step 3: Fetch user object
108
111
  let accounts = { currentAccount: null, accounts: [] };
109
112
  if (fs.existsSync(ACCOUNTS_PATH)) {
110
- const data = fs.readFileSync(ACCOUNTS_PATH, "utf8");
111
- accounts = JSON.parse(data);
113
+ const data = fs.readFileSync(ACCOUNTS_PATH, "utf8");
114
+ accounts = JSON.parse(data);
112
115
  }
113
116
  const userRes = await fetch(`https://${AUTH0_DOMAIN}/userinfo`, {
114
- headers: {
115
- Authorization: `Bearer ${tokenData.access_token}`,
116
- },
117
+ headers: {
118
+ Authorization: `Bearer ${tokenData.access_token}`,
119
+ },
117
120
  });
118
121
  const userData = await userRes.json();
119
122
  if (!accounts.currentAccount) {
120
- await fs.promises.writeFile(ACCOUNTS_PATH, JSON.stringify({
121
- currentAccount: userData.email,
122
- accounts: [userData.email],
123
- }));
124
- }
125
- else if (accounts.currentAccount !== userData.email) {
126
- accounts.currentAccount = userData.email;
127
- await fs.promises.writeFile(ACCOUNTS_PATH, JSON.stringify({
128
- currentAccount: userData.email,
129
- accounts: [userData.email, ...accounts.accounts],
130
- }));
123
+ await fs.promises.writeFile(
124
+ ACCOUNTS_PATH,
125
+ JSON.stringify({
126
+ currentAccount: userData.email,
127
+ accounts: [userData.email],
128
+ }),
129
+ );
130
+ } else if (accounts.currentAccount !== userData.email) {
131
+ accounts.currentAccount = userData.email;
132
+ await fs.promises.writeFile(
133
+ ACCOUNTS_PATH,
134
+ JSON.stringify({
135
+ currentAccount: userData.email,
136
+ accounts: [userData.email, ...accounts.accounts],
137
+ }),
138
+ );
131
139
  }
132
140
  // Step 4: Store token securely
133
141
  tokenData.obtained_at = Math.floor(Date.now() / 1000);
134
142
  await saveTokens(userData.email, tokenData);
135
143
  consola.success("Login successful! Access token stored securely.");
136
- });
144
+ });
137
145
  // Example usage: get a valid access token
138
146
  export async function ensureToken() {
139
- const accessToken = await refreshTokenIfNeeded();
140
- if (!accessToken) {
141
- consola.error("Not authenticated. Please run 'login' first.");
142
- process.exit(1);
143
- }
144
- return accessToken;
147
+ const accessToken = await refreshTokenIfNeeded();
148
+ if (!accessToken) {
149
+ consola.error("Not authenticated. Please run 'login' first.");
150
+ process.exit(1);
151
+ }
152
+ return accessToken;
145
153
  }
@@ -20,3 +20,14 @@ export const fetchManagementApi = async (path, method = "GET", body) => {
20
20
  consola.debug("Response:", JSON.stringify(result));
21
21
  return result;
22
22
  };
23
+ export const singleton = (fn) => {
24
+ let running = null;
25
+ return async () => {
26
+ if (!running) {
27
+ running = fn().finally(() => {
28
+ running = null;
29
+ });
30
+ }
31
+ return running;
32
+ };
33
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nlxai/cli",
3
- "version": "1.2.2-alpha.8",
3
+ "version": "1.2.3-alpha.0",
4
4
  "description": "Tools for integrating with NLX apps",
5
5
  "keywords": [
6
6
  "NLX",
@@ -58,5 +58,5 @@
58
58
  "@vitest/ui": "^3.2.4",
59
59
  "vitest": "^3.2.4"
60
60
  },
61
- "gitHead": "2829feb4c0a570906493c8f6d8671b14886d705c"
61
+ "gitHead": "2e39f684bb39b0ccbed58486a4f82f93693218ca"
62
62
  }