@solti/cli 0.1.1 → 0.1.2

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.
@@ -1,32 +1,69 @@
1
1
  /**
2
2
  * LogTo OAuth 2.0 Authorization Code + PKCE flow for the Solti CLI.
3
3
  *
4
- * Registered client (Change 004 — see
5
- * solti-specs/changes/004--easier-platform-access/logto-changes.md):
6
- * - "Solti CLI" native app, public client (no secret)
7
- * - Redirect URIs: http://localhost:4242..4245/callback (exact-match; no wildcards)
8
- * - Resource `https://api.solti.run` so access tokens are verifiable JWTs
4
+ * Registered clients (Change 004; live apps replicated in Change 007):
5
+ * - live LogTo (https://auth.solti.run/oidc): "Solti CLI" native app `1mo3mre0396x2a1ux5q93`
6
+ * - dev LogTo (https://auth.dev.solti.run/oidc): "Solti CLI" native app `sae2x70zlqqv4qs3gw6cu`
7
+ * - Public clients (no secret); redirect URIs http://localhost:4242..4245/callback
8
+ * (exact-match; no wildcards); resource `https://api.solti.run` so access
9
+ * tokens are verifiable JWTs.
10
+ *
11
+ * The DEFAULT issuer is the live one: the CLI's default API host is the live
12
+ * `https://api.solti.run/1`, and the live API rejects dev-issued tokens
13
+ * ("Missing user context for project scope" / "User is not authenticated")
14
+ * — the previous dev default made plain `solti account login` unusable
15
+ * against the default API (Change 048). Dev-issuer sign-in remains available
16
+ * via SOLTI_LOGTO_ISSUER / SOLTI_LOGTO_CLIENT_ID. Whichever environment a
17
+ * login used is persisted per account (AuthStore.issuer/client_id) so token
18
+ * refresh and logout hit the same LogTo instance.
9
19
  */
10
20
  import crypto from "node:crypto";
11
21
  import http from "node:http";
12
22
  import { deleteAuth, getActiveAccount, listAccounts, readActive, readAuth, writeActive, writeAuth, } from "../config/store.js";
13
- export const CLIENT_ID = process.env.SOLTI_LOGTO_CLIENT_ID ?? "sae2x70zlqqv4qs3gw6cu";
14
- export const ISSUER = process.env.SOLTI_LOGTO_ISSUER ?? "https://auth.dev.solti.run/oidc";
23
+ export const CLIENT_ID = process.env.SOLTI_LOGTO_CLIENT_ID ?? "1mo3mre0396x2a1ux5q93";
24
+ export const ISSUER = process.env.SOLTI_LOGTO_ISSUER ?? "https://auth.solti.run/oidc";
15
25
  export const RESOURCE = process.env.SOLTI_LOGTO_RESOURCE ?? "https://api.solti.run";
16
26
  export const SCOPES = "openid profile email offline_access";
27
+ /** Decodes JWT payload claims (no signature check — best-effort hints only). */
28
+ function decodeJwtClaims(token) {
29
+ if (token === undefined)
30
+ return null;
31
+ const parts = token.split(".");
32
+ if (parts.length !== 3)
33
+ return null;
34
+ try {
35
+ return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ /** Per-account OIDC resolution for refresh/logout (pure — unit-tested). */
42
+ export function resolveOidc(auth) {
43
+ const claims = decodeJwtClaims(auth.access_token);
44
+ const issuer = auth.issuer ??
45
+ (typeof claims?.iss === "string" && claims.iss !== "" ? claims.iss : null) ??
46
+ ISSUER;
47
+ const clientId = auth.client_id ??
48
+ (typeof claims?.client_id === "string" && claims.client_id !== "" ? claims.client_id : null) ??
49
+ CLIENT_ID;
50
+ return { issuer, clientId };
51
+ }
17
52
  /** Fixed registered loopback port range (spec §1.1 / logto-changes.md §5.1). */
18
53
  const CALLBACK_PORTS = [4242, 4243, 4244, 4245];
19
54
  const CALLBACK_PATH = "/callback";
20
- let discoveryCache = null;
21
- export async function discover() {
22
- if (discoveryCache !== null)
23
- return discoveryCache;
24
- const response = await fetch(`${ISSUER}/.well-known/openid-configuration`);
55
+ const discoveryCache = new Map();
56
+ export async function discover(issuer = ISSUER) {
57
+ const cached = discoveryCache.get(issuer);
58
+ if (cached !== undefined)
59
+ return cached;
60
+ const response = await fetch(`${issuer}/.well-known/openid-configuration`);
25
61
  if (!response.ok) {
26
62
  throw new Error(`Failed to discover LogTo OIDC configuration (HTTP ${response.status})`);
27
63
  }
28
- discoveryCache = (await response.json());
29
- return discoveryCache;
64
+ const discovery = (await response.json());
65
+ discoveryCache.set(issuer, discovery);
66
+ return discovery;
30
67
  }
31
68
  function base64url(buffer) {
32
69
  return buffer.toString("base64url");
@@ -94,6 +131,10 @@ export async function login(options) {
94
131
  expires_at: new Date(Date.now() + tokens.expires_in * 1000).toISOString(),
95
132
  token_type: tokens.token_type ?? "Bearer",
96
133
  email,
134
+ // Persist the environment this login used so refresh/logout stay on the
135
+ // same LogTo instance (Change 048).
136
+ issuer: ISSUER,
137
+ client_id: CLIENT_ID,
97
138
  };
98
139
  await writeAuth(email, auth);
99
140
  // Switch the active account (adds the account if another one was active).
@@ -230,14 +271,15 @@ export async function ensureFreshAccessToken(email) {
230
271
  if (auth.refresh_token === "") {
231
272
  throw new Error(`Session for ${email} expired and no refresh token is stored. Run \`solti account login\`.`);
232
273
  }
233
- const oidc = await discover();
274
+ const { issuer, clientId } = resolveOidc(auth);
275
+ const oidc = await discover(issuer);
234
276
  const response = await fetch(oidc.token_endpoint, {
235
277
  method: "POST",
236
278
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
237
279
  body: new URLSearchParams({
238
280
  grant_type: "refresh_token",
239
281
  refresh_token: auth.refresh_token,
240
- client_id: CLIENT_ID,
282
+ client_id: clientId,
241
283
  // LogTo does not auto-reuse the grant's resource (useGrantedResource=false)
242
284
  // — the refreshed access token must explicitly request it to stay a JWT.
243
285
  resource: RESOURCE,
@@ -253,6 +295,9 @@ export async function ensureFreshAccessToken(email) {
253
295
  // LogTo rotates refresh tokens on use — persist the new one.
254
296
  refresh_token: tokens.refresh_token ?? auth.refresh_token,
255
297
  expires_at: new Date(Date.now() + tokens.expires_in * 1000).toISOString(),
298
+ // Stamp the resolved environment so legacy auth.json entries are upgraded.
299
+ issuer,
300
+ client_id: clientId,
256
301
  };
257
302
  await writeAuth(email, updated);
258
303
  return updated.access_token;
@@ -262,12 +307,13 @@ export async function logout(email) {
262
307
  const auth = await readAuth(email);
263
308
  if (auth !== null && auth.refresh_token !== "") {
264
309
  try {
265
- const oidc = await discover();
310
+ const { issuer, clientId } = resolveOidc(auth);
311
+ const oidc = await discover(issuer);
266
312
  if (oidc.revocation_endpoint !== undefined) {
267
313
  await fetch(oidc.revocation_endpoint, {
268
314
  method: "POST",
269
315
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
270
- body: new URLSearchParams({ token: auth.refresh_token, client_id: CLIENT_ID }),
316
+ body: new URLSearchParams({ token: auth.refresh_token, client_id: clientId }),
271
317
  });
272
318
  }
273
319
  }
@@ -1,13 +1,17 @@
1
1
  import fs from "node:fs";
2
2
  import { request } from "../api/client.js";
3
- import { parseEnvFile, parseResources, parseVolumeShorthand } from "../lib/parse.js";
3
+ import { parseEnvFile, parseResources, parseStringList, parseVolumeShorthand } from "../lib/parse.js";
4
4
  export async function jobList(options = {}) {
5
5
  // API filters (jobs/dtos.py ListJobsRequest): repeatable `tag=` and
6
6
  // `label=` query params; labels are "key:value" ("key=value" accepted).
7
+ // Commander keeps a non-collect option as a scalar when used once, so
8
+ // coerce to arrays here (a bare string would otherwise iterate chars).
9
+ const tags = parseStringList(options.tag);
10
+ const labels = parseStringList(options.label);
7
11
  const query = new URLSearchParams();
8
- for (const tag of options.tag ?? [])
12
+ for (const tag of tags)
9
13
  query.append("tag", tag);
10
- for (const label of options.label ?? []) {
14
+ for (const label of labels) {
11
15
  if (!label.includes(":") && !label.includes("=")) {
12
16
  throw new Error(`Invalid --label '${label}' — expected key:value (or key=value)`);
13
17
  }
@@ -122,8 +126,11 @@ export async function jobRun(options) {
122
126
  })),
123
127
  labels: Object.fromEntries((options.label ?? []).map((l) => l.split("=", 2))),
124
128
  tags: options.tag,
125
- cloud: options.cloud,
126
- region: options.region,
129
+ // Arrays only — Change 048: the API accepts the documented scalar form
130
+ // (`cloud: aws`) but a scalar JSON string in jobs.cloud 500s every
131
+ // /1/jobs* read, so the CLI always sends arrays.
132
+ cloud: parseStringList(options.cloud).length > 0 ? parseStringList(options.cloud) : undefined,
133
+ region: parseStringList(options.region).length > 0 ? parseStringList(options.region) : undefined,
127
134
  };
128
135
  if (options.resources !== undefined) {
129
136
  const parsed = parseResources(options.resources);
package/dist/index.js CHANGED
@@ -13,13 +13,19 @@ const program = new Command();
13
13
  program
14
14
  .name("solti")
15
15
  .description("Solti Platform CLI — schedule and run asynchronous workloads without managing infrastructure.")
16
- .version("0.1.1")
16
+ .version("0.1.2")
17
17
  .option("--profile <name>", "override the active profile (or set SOLTI_PROFILE)")
18
18
  .option("--api-key <key>", "override the API key (or set SOLTI_API_KEY)");
19
19
  function fail(error) {
20
20
  console.error(`error: ${error.message}`);
21
21
  process.exit(1);
22
22
  }
23
+ /** Commander collector for repeatable valued options: each occurrence appends
24
+ * (plain non-collect options overwrite — last value wins). Comma-separated
25
+ * values stay joined here; commands split them via parseStringList. */
26
+ function collectValues(value, previous) {
27
+ return [...previous, value];
28
+ }
23
29
  // --- account ----------------------------------------------------------------
24
30
  const accountCommand = program.command("account").description("Manage logged-in accounts");
25
31
  accountCommand
@@ -187,8 +193,8 @@ jobCommand
187
193
  .option("--resources <spec>", "e.g. cpu=4,memory=16Gi,gpu=24Gi or gpu.model=A100,gpu.count=2")
188
194
  .option("--label <key=value>", "label (repeatable)")
189
195
  .option("--tag <tag>", "tag (repeatable)")
190
- .option("--cloud <provider>", "cloud constraint (aws | gcp | azure)")
191
- .option("--region <region>", "region constraint")
196
+ .option("--cloud <provider>", "cloud constraint (aws | gcp | azure; repeatable or comma-separated)", collectValues, [])
197
+ .option("--region <region>", "region constraint (repeatable or comma-separated)", collectValues, [])
192
198
  .allowUnknownOption(true)
193
199
  .argument("[operands...]", "positional command and args (after --)")
194
200
  .action(async (_operands, options, command) => {
package/dist/lib/parse.js CHANGED
@@ -2,6 +2,18 @@
2
2
  * Pure parsers for `solti job run` flag payloads (constitution tools/cli.md
3
3
  * §2.2). Kept free of I/O so they can be unit-tested directly (tests/parse.test.ts).
4
4
  */
5
+ /** Normalizes repeatable + comma-separated flag values (cli.md §2.2:
6
+ * `--cloud aws,gcp` and `--cloud aws --cloud gcp` are both valid). Returns a
7
+ * flat, trimmed, empty-item-free array so the API always receives a JSON
8
+ * array — a scalar `cloud`/`region` payload is what poisoned jobs.cloud on
9
+ * the live API (Change 048). */
10
+ export function parseStringList(values) {
11
+ const list = values === undefined ? [] : Array.isArray(values) ? values : [values];
12
+ return list
13
+ .flatMap((value) => value.split(","))
14
+ .map((value) => value.trim())
15
+ .filter((value) => value !== "");
16
+ }
5
17
  /** Parses `.env`-style content: KEY=VALUE lines; blank lines and `#`
6
18
  * comments are ignored; whitespace is trimmed; matching surrounding quotes
7
19
  * are stripped from values. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@solti/cli",
3
- "version": "0.1.1",
4
- "description": "Solti Platform CLI — schedule and run asynchronous workloads without managing infrastructure.",
3
+ "version": "0.1.2",
4
+ "description": "Solti Platform CLI \u2014 schedule and run asynchronous workloads without managing infrastructure.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "files": [