@solidactions/cli 1.31.1 → 1.33.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.
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.requestDeviceCode = requestDeviceCode;
7
+ exports.pollForToken = pollForToken;
8
+ exports.deviceLogin = deviceLogin;
9
+ const axios_1 = __importDefault(require("axios"));
10
+ const chalk_1 = __importDefault(require("chalk"));
11
+ const workspace_lookup_1 = require("../utils/workspace-lookup");
12
+ const login_1 = require("./login");
13
+ // Public device-flow client id — not a secret; matches the server-seeded
14
+ // oauth_clients row (config('services.cli.oauth_client_id') on the app side).
15
+ const CLI_OAUTH_CLIENT_ID = '9f1b6e2a-9c1e-4b6e-8f0a-6c9f2b1e7d4c';
16
+ // CLI capability scopes requested at device-code issuance — the server
17
+ // rejects any scope not pre-registered via Passport::tokensCan().
18
+ const CLI_SCOPES = 'env deploy runs docs';
19
+ async function requestDeviceCode(host) {
20
+ const response = await axios_1.default.post(`${host}/oauth/device/code`, {
21
+ client_id: CLI_OAUTH_CLIENT_ID,
22
+ scope: CLI_SCOPES,
23
+ });
24
+ return response.data;
25
+ }
26
+ function sleep(ms) {
27
+ return new Promise((resolve) => setTimeout(resolve, ms));
28
+ }
29
+ /**
30
+ * Poll POST /oauth/token per RFC 8628 §3.5: repeat at `intervalSeconds`,
31
+ * honoring `authorization_pending` (keep polling) and `slow_down` (add
32
+ * `slowDownIncrementSeconds` to the interval and keep polling). Rejects on
33
+ * any other OAuth error, including a server-sent `expired_token`.
34
+ * `slowDownIncrementSeconds` defaults to the RFC-recommended 5s and is only
35
+ * overridden by tests, to keep them fast.
36
+ *
37
+ * `expiresInSeconds` bounds the loop client-side to the device code's own
38
+ * lifetime, so a server that never emits `expired_token` (and just keeps
39
+ * returning `authorization_pending`) can't cause an infinite poll.
40
+ */
41
+ async function pollForToken(host, clientId, deviceCode, intervalSeconds, expiresInSeconds, slowDownIncrementSeconds = 5) {
42
+ let interval = intervalSeconds;
43
+ let elapsed = 0;
44
+ while (true) {
45
+ if (elapsed + interval > expiresInSeconds) {
46
+ throw new Error('device code expired — run `solidactions login --device` again');
47
+ }
48
+ await sleep(interval * 1000);
49
+ elapsed += interval;
50
+ try {
51
+ const response = await axios_1.default.post(`${host}/oauth/token`, {
52
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
53
+ device_code: deviceCode,
54
+ client_id: clientId,
55
+ });
56
+ return response.data;
57
+ }
58
+ catch (error) {
59
+ const oauthError = error?.response?.data?.error;
60
+ if (oauthError === 'authorization_pending') {
61
+ continue;
62
+ }
63
+ if (oauthError === 'slow_down') {
64
+ interval += slowDownIncrementSeconds;
65
+ continue;
66
+ }
67
+ if (oauthError === 'expired_token') {
68
+ throw new Error('device code expired — run `solidactions login --device` again');
69
+ }
70
+ throw new Error(oauthError || error.message);
71
+ }
72
+ }
73
+ }
74
+ async function deviceLogin(options) {
75
+ const resolved = (0, login_1.resolveLoginHost)(options);
76
+ const host = resolved.host;
77
+ console.log(chalk_1.default.blue('Requesting device authorization...'));
78
+ const code = await requestDeviceCode(host);
79
+ const verifyUrl = code.verification_uri_complete || code.verification_uri;
80
+ console.log('');
81
+ console.log(chalk_1.default.green('To finish signing in, visit:'));
82
+ console.log(' ' + chalk_1.default.blue.underline(verifyUrl));
83
+ console.log(chalk_1.default.gray(' Enter code: ') + chalk_1.default.bold(code.user_code));
84
+ console.log('');
85
+ console.log(chalk_1.default.gray('Waiting for approval in your browser...'));
86
+ let token;
87
+ try {
88
+ token = await pollForToken(host, CLI_OAUTH_CLIENT_ID, code.device_code, code.interval || 5, code.expires_in);
89
+ }
90
+ catch (error) {
91
+ console.error(chalk_1.default.red('Device login failed:'), error.message);
92
+ process.exit(1);
93
+ return;
94
+ }
95
+ const config = { host, apiKey: token.access_token };
96
+ // Same tail as login(): fetch workspaces, then resolve + write + report
97
+ // exactly as login() does via the shared completeLogin() helper.
98
+ let workspaces;
99
+ let scope;
100
+ try {
101
+ ({ workspaces, scope } = await (0, workspace_lookup_1.fetchWorkspaces)(config));
102
+ }
103
+ catch (e) {
104
+ if (e.response?.status === 401) {
105
+ console.error(chalk_1.default.red(`Invalid API key for ${host}.`));
106
+ }
107
+ else {
108
+ console.error(chalk_1.default.red(`Could not reach ${host}: ${e.message}`));
109
+ }
110
+ process.exit(1);
111
+ return;
112
+ }
113
+ await (0, login_1.completeLogin)(config, workspaces, options, scope);
114
+ }
@@ -11,6 +11,7 @@ exports.clearConfig = clearConfig;
11
11
  exports.resolveLoginHost = resolveLoginHost;
12
12
  exports.backupPathFor = backupPathFor;
13
13
  exports.loginHostLines = loginHostLines;
14
+ exports.completeLogin = completeLogin;
14
15
  exports.login = login;
15
16
  exports.logout = logout;
16
17
  exports.whoami = whoami;
@@ -139,36 +140,17 @@ async function selectWorkspaceInteractively(workspaces) {
139
140
  }
140
141
  return workspaces[index];
141
142
  }
142
- async function login(apiKey, options) {
143
- const resolved = resolveLoginHost(options);
144
- const host = resolved.host;
145
- if (!apiKey || apiKey.trim().length === 0) {
146
- console.error(chalk_1.default.red('Error: API key is required.'));
147
- console.log(chalk_1.default.gray('Generate an API key at: ') + chalk_1.default.blue(`${host}/settings/api-keys`));
148
- process.exit(1);
149
- }
150
- console.log(chalk_1.default.blue(`Initializing SolidActions CLI...`));
151
- for (const line of loginHostLines(resolved)) {
152
- console.log(resolved.isDefault ? chalk_1.default.yellow(line) : chalk_1.default.gray(line));
153
- }
154
- const config = {
155
- host,
156
- apiKey: apiKey.trim(),
157
- };
158
- // 1. Validate the key BEFORE any disk write.
159
- let workspaces;
160
- try {
161
- workspaces = await (0, workspace_lookup_1.fetchWorkspaces)(config);
162
- }
163
- catch (e) {
164
- if (e.response?.status === 401) {
165
- console.error(chalk_1.default.red(`Invalid API key for ${host}.`));
166
- }
167
- else {
168
- console.error(chalk_1.default.red(`Could not reach ${host}: ${e.message}`));
169
- }
170
- process.exit(1);
171
- return;
143
+ /**
144
+ * Shared tail of `login`, reused verbatim by `deviceLogin`: resolve the
145
+ * workspace against an already-fetched list, determine the write target,
146
+ * back up + write the config file once, and print the success output.
147
+ */
148
+ async function completeLogin(config, workspaces, options, scope = null) {
149
+ // Device-flow tokens carry a scope (mode + workspace_ids) that later
150
+ // gates `workspace set`; absent for user-scoped Sanctum PATs.
151
+ if (scope) {
152
+ config.scopeMode = scope.mode;
153
+ config.scopedWorkspaceIds = scope.workspace_ids;
172
154
  }
173
155
  // 2. Resolve the workspace (still before writing).
174
156
  if (options.workspace) {
@@ -222,6 +204,40 @@ async function login(apiKey, options) {
222
204
  console.log(chalk_1.default.gray(' solidactions run start <proj> <wf> Run a workflow'));
223
205
  console.log(chalk_1.default.gray(' solidactions run list List recent runs'));
224
206
  }
207
+ async function login(apiKey, options) {
208
+ const resolved = resolveLoginHost(options);
209
+ const host = resolved.host;
210
+ if (!apiKey || apiKey.trim().length === 0) {
211
+ console.error(chalk_1.default.red('Error: API key is required.'));
212
+ console.log(chalk_1.default.gray('Generate an API key at: ') + chalk_1.default.blue(`${host}/settings/api-keys`));
213
+ process.exit(1);
214
+ }
215
+ console.log(chalk_1.default.blue(`Initializing SolidActions CLI...`));
216
+ for (const line of loginHostLines(resolved)) {
217
+ console.log(resolved.isDefault ? chalk_1.default.yellow(line) : chalk_1.default.gray(line));
218
+ }
219
+ const config = {
220
+ host,
221
+ apiKey: apiKey.trim(),
222
+ };
223
+ // 1. Validate the key BEFORE any disk write.
224
+ let workspaces;
225
+ let scope;
226
+ try {
227
+ ({ workspaces, scope } = await (0, workspace_lookup_1.fetchWorkspaces)(config));
228
+ }
229
+ catch (e) {
230
+ if (e.response?.status === 401) {
231
+ console.error(chalk_1.default.red(`Invalid API key for ${host}.`));
232
+ }
233
+ else {
234
+ console.error(chalk_1.default.red(`Could not reach ${host}: ${e.message}`));
235
+ }
236
+ process.exit(1);
237
+ return;
238
+ }
239
+ await completeLogin(config, workspaces, options, scope);
240
+ }
225
241
  function logout(options = {}) {
226
242
  if (options.local && options.global) {
227
243
  console.error(chalk_1.default.red('Error: --local and --global are mutually exclusive.'));
@@ -54,6 +54,10 @@ async function workspacesList() {
54
54
  process.exit(1);
55
55
  }
56
56
  }
57
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
58
+ function looksLikeUuid(input) {
59
+ return UUID_RE.test(input);
60
+ }
57
61
  async function workspaceSet(input, options = {}) {
58
62
  if (process.env.SOLIDACTIONS_WORKSPACE_ID) {
59
63
  console.error(chalk_1.default.red('SOLIDACTIONS_WORKSPACE_ID is set in the environment; the change would not take effect. ' +
@@ -61,6 +65,18 @@ async function workspaceSet(input, options = {}) {
61
65
  process.exit(1);
62
66
  }
63
67
  const config = (0, api_1.requireResolvedConfig)().config;
68
+ if ((config.scopeMode === 'single' || config.scopeMode === 'subset') && config.scopedWorkspaceIds) {
69
+ // Best-effort pre-check: the scope list holds raw ids, so only an id
70
+ // input can be checked locally; slug/name inputs fall through to the
71
+ // server's authoritative 403 workspace_forbidden (surfaced cleanly).
72
+ const isKnownOutOfScope = config.scopedWorkspaceIds.length > 0
73
+ && !config.scopedWorkspaceIds.includes(input);
74
+ if (isKnownOutOfScope && looksLikeUuid(input)) {
75
+ console.error(chalk_1.default.red(`This session is scoped to workspace(s) ${config.scopedWorkspaceIds.join(', ')}. `
76
+ + 'Re-run `solidactions login --device` to change scope.'));
77
+ process.exit(1);
78
+ }
79
+ }
64
80
  const workspace = await (0, workspace_lookup_1.resolveWorkspaceInput)(config, input);
65
81
  const target = await (0, config_write_target_1.decideWriteTarget)({ local: options.local, global: options.global });
66
82
  const targetPath = (0, config_write_target_1.pathForTarget)(target);
package/dist/index.js CHANGED
@@ -1,5 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
3
36
  var __importDefault = (this && this.__importDefault) || function (mod) {
4
37
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
38
  };
@@ -108,16 +141,27 @@ program.hook('preAction', (thisCommand, actionCommand) => {
108
141
  // =============================================================================
109
142
  program
110
143
  .command('login')
111
- .description('Authenticate the CLI (prompts securely for your API key)')
112
- .argument('[api-key]', 'Legacy positional API key (prefer the masked prompt or --stdin)')
144
+ .description('Authenticate the CLI (prompts securely for your API key, or via --device for browser-based login)')
145
+ .argument('[api-key]', 'Legacy positional API key (prefer the masked prompt, --stdin, or --device)')
113
146
  .option('--stdin', 'Read the API key from stdin (for non-interactive automation)')
147
+ .option('--device', 'Authenticate via browser using OAuth device authorization')
114
148
  .option('--dev', 'Use local development server (http://localhost:8000)')
115
149
  .option('--host <url>', 'Custom API host URL')
116
150
  .option('--workspace <name-or-id>', 'Set workspace by name, slug, or ID (skips interactive prompt). Non-interactive logins without this flag leave the workspace unset.')
117
151
  .option('--local', 'Save config to ./.solidactions/config.json in the current folder')
118
152
  .option('--global', 'Save config to ~/.solidactions/config.json (default if prompted)')
119
153
  .option('--gitignore', 'With --local, add .solidactions/ to .gitignore without prompting')
154
+ .addHelpText('after', `
155
+ Environment:
156
+ SOLIDACTIONS_API_KEY When set, this key takes precedence over any saved
157
+ credentials and is used directly — you do not need to run
158
+ \`login\` (or \`login --device\`) at all in that setup.`)
120
159
  .action(async (apiKey, options) => {
160
+ if (options.device) {
161
+ const { deviceLogin } = await Promise.resolve().then(() => __importStar(require('./commands/device-login')));
162
+ await deviceLogin(options);
163
+ return;
164
+ }
121
165
  const resolvedApiKey = await (0, login_1.resolveLoginApiKey)(apiKey, { stdin: options.stdin });
122
166
  await (0, login_1.login)(resolvedApiKey, options);
123
167
  });
@@ -443,9 +487,14 @@ workspace
443
487
  .command('set')
444
488
  .description('Set the active workspace and pin it')
445
489
  .argument('<id-or-slug-or-name>', 'Workspace ID, slug, or name')
446
- .option('--local', 'pin to ./.solidactions/config.json')
447
- .option('--global', 'pin to ~/.solidactions/config.json')
490
+ .option('--local', 'pin to ./.solidactions/config.json (this folder only)')
491
+ .option('--global', 'pin to ~/.solidactions/config.json (machine-wide)')
448
492
  .option('--gitignore', 'auto-add .solidactions/ to local .gitignore (skip prompt)')
493
+ .addHelpText('after', `
494
+ Where the pin is saved (--local / --global):
495
+ --local and --global choose the target file and are mutually exclusive.
496
+ If neither is passed, you are prompted when interactive (default: global);
497
+ in non-interactive/CI use, the command exits with an error asking you to pass one.`)
449
498
  .action(async (input, opts) => {
450
499
  await (0, workspaces_1.workspaceSet)(input, opts);
451
500
  });
package/dist/utils/api.js CHANGED
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.augmentNotFoundMessage = augmentNotFoundMessage;
7
+ exports.augmentWorkspaceForbiddenMessage = augmentWorkspaceForbiddenMessage;
7
8
  exports.getApiHeaders = getApiHeaders;
8
9
  exports.describeProjectEnvironments = describeProjectEnvironments;
9
10
  exports.formatValidationError = formatValidationError;
@@ -37,7 +38,23 @@ function augmentNotFoundMessage(error) {
37
38
  }
38
39
  return error;
39
40
  }
40
- axios_1.default.interceptors.response.use((response) => response, (error) => Promise.reject(augmentNotFoundMessage(error)));
41
+ /**
42
+ * Inspect an axios error and, if it's a 403 with the app's `workspace_forbidden`
43
+ * error code (device-flow-scoped token targeting a workspace outside its
44
+ * scope), replace the raw server message with actionable guidance similar in
45
+ * spirit to `workspaceSet`'s local pre-check (wording isn't kept in sync
46
+ * verbatim) — so slug/name inputs (which can't be pre-checked locally) still
47
+ * surface a clear message instead of a raw axios/HTTP error.
48
+ */
49
+ function augmentWorkspaceForbiddenMessage(error) {
50
+ if (error?.response?.status === 403 && error.response.data?.code === 'workspace_forbidden') {
51
+ error.response.data.message =
52
+ 'This session is scoped to a limited set of workspaces. '
53
+ + 'Re-run `solidactions login --device` to change scope.';
54
+ }
55
+ return error;
56
+ }
57
+ axios_1.default.interceptors.response.use((response) => response, (error) => Promise.reject(augmentWorkspaceForbiddenMessage(augmentNotFoundMessage(error))));
41
58
  function getApiHeaders(config, contentType) {
42
59
  const headers = {
43
60
  'Authorization': `Bearer ${config.apiKey}`,
@@ -157,6 +174,11 @@ async function ensureWorkspaceSelected(config) {
157
174
  else {
158
175
  workspaces = Array.isArray(grouped) ? grouped : [];
159
176
  }
177
+ const scope = response.data.scope;
178
+ if (scope) {
179
+ config.scopeMode = scope.mode;
180
+ config.scopedWorkspaceIds = scope.workspace_ids;
181
+ }
160
182
  }
161
183
  catch (error) {
162
184
  if (error.response?.status === 401) {
@@ -168,6 +168,9 @@ function mergeConfigs(env, local, localPath, global, globalPath) {
168
168
  };
169
169
  const workspace = pickWorkspaceField('workspace');
170
170
  const workspaceId = pickWorkspaceField('workspaceId');
171
+ // Never env-settable — config-file layers only (local > global).
172
+ const scopeMode = pick('scopeMode');
173
+ const scopedWorkspaceIds = pick('scopedWorkspaceIds');
171
174
  if (!host.value && !apiKey.value) {
172
175
  return null;
173
176
  }
@@ -177,6 +180,8 @@ function mergeConfigs(env, local, localPath, global, globalPath) {
177
180
  apiKey: (apiKey.value ?? ''),
178
181
  workspace: workspace.value,
179
182
  workspaceId: workspaceId.value,
183
+ scopeMode: scopeMode.value,
184
+ scopedWorkspaceIds: scopedWorkspaceIds.value,
180
185
  },
181
186
  sources: {
182
187
  host: host.source,
@@ -38,7 +38,8 @@ async function fetchWorkspaces(config) {
38
38
  else if (Array.isArray(grouped)) {
39
39
  out.push(...grouped);
40
40
  }
41
- return out;
41
+ const scope = response.data.scope ?? null;
42
+ return { workspaces: out, scope };
42
43
  }
43
44
  /**
44
45
  * High-level: fetch + match. Errors with a clear CLI message and exits
@@ -46,8 +47,9 @@ async function fetchWorkspaces(config) {
46
47
  */
47
48
  async function resolveWorkspaceInput(config, input) {
48
49
  let workspaces;
50
+ let scope = null;
49
51
  try {
50
- workspaces = await fetchWorkspaces(config);
52
+ ({ workspaces, scope } = await fetchWorkspaces(config));
51
53
  }
52
54
  catch (error) {
53
55
  console.error(chalk_1.default.red('Failed to list workspaces:'), error.response?.data?.message || error.message);
@@ -55,7 +57,18 @@ async function resolveWorkspaceInput(config, input) {
55
57
  }
56
58
  const match = matchWorkspace(input, workspaces);
57
59
  if (!match) {
58
- console.error(chalk_1.default.red(`Workspace "${input}" not found. Run \`solidactions workspace list\` to list available workspaces.`));
60
+ // A scoped (single/subset) session only ever lists the workspaces its
61
+ // OAuth grant covers, so a miss can mean either "doesn't exist" OR
62
+ // "exists but out of this session's scope" — disambiguate so the user
63
+ // knows re-auth with broader scope may be the fix, not a typo.
64
+ if (scope && (scope.mode === 'single' || scope.mode === 'subset')) {
65
+ console.error(chalk_1.default.red(`Workspace "${input}" not found in this session's authorized workspaces `
66
+ + `(scope: ${scope.mode}${scope.workspace_ids.length ? `, covering ${scope.workspace_ids.join(', ')}` : ''}). `
67
+ + 'If it exists but is out of scope, re-authenticate with broader scope: `solidactions login --device`.'));
68
+ }
69
+ else {
70
+ console.error(chalk_1.default.red(`Workspace "${input}" not found. Run \`solidactions workspace list\` to list available workspaces.`));
71
+ }
59
72
  process.exit(1);
60
73
  }
61
74
  return match;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidactions/cli",
3
- "version": "1.31.1",
3
+ "version": "1.33.0",
4
4
  "description": "SolidActions CLI - Deploy and manage workflow automation",
5
5
  "main": "dist/index.js",
6
6
  "bin": {