@solti/cli 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +57 -2
- package/dist/api/client.js +166 -0
- package/dist/auth/oauth.js +342 -0
- package/dist/commands/account.js +87 -0
- package/dist/commands/connection.js +59 -0
- package/dist/commands/cronjob.js +81 -0
- package/dist/commands/job.js +155 -0
- package/dist/commands/key.js +32 -0
- package/dist/commands/organization.js +59 -0
- package/dist/commands/profile.js +83 -0
- package/dist/commands/project.js +101 -0
- package/dist/commands/resource.js +26 -0
- package/dist/config/paths.js +25 -0
- package/dist/config/store.js +97 -0
- package/dist/index.js +329 -0
- package/dist/lib/parse.js +136 -0
- package/package.json +29 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Solti
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Solti CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Command-line interface for the [Solti Platform](https://solti.run) — schedule and run asynchronous workloads without managing infrastructure.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
brew install trysolti/tap/solti
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Or via Node.js (>= 20) with npm / pnpm:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install -g @solti/cli
|
|
15
|
+
# or: pnpm add -g @solti/cli
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quickstart
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
solti account login # opens your browser — sign in once
|
|
22
|
+
solti organization list
|
|
23
|
+
solti project list
|
|
24
|
+
solti profile set default --project-id <your-project-id>
|
|
25
|
+
solti job run --image alpine:latest -- echo "Hello from Solti!"
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Headless / CI usage (no login required):
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
export SOLTI_API_KEY=<your-api-key>
|
|
32
|
+
export SOLTI_PROJECT_ID=<your-project-id>
|
|
33
|
+
solti job list
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Configuration
|
|
37
|
+
|
|
38
|
+
State is stored under `~/.solti/`:
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
~/.solti/
|
|
42
|
+
├── active.json # active account + active profile
|
|
43
|
+
└── accounts/
|
|
44
|
+
└── <email>/
|
|
45
|
+
├── auth.json # OAuth tokens (0600)
|
|
46
|
+
└── profiles/
|
|
47
|
+
└── <profile>/config.json
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Development
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pnpm install
|
|
54
|
+
pnpm build
|
|
55
|
+
node dist/index.js --help
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Spec: `../solti-specs/constitution/tools/cli.md` (implementation tracked under Change 004).
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Solti API client — credential resolution (spec §1.1) + endpoint resolution.
|
|
3
|
+
*
|
|
4
|
+
* 1. `--api-key` flag / `SOLTI_API_KEY` (+ `SOLTI_PROJECT_ID`) env vars → API Key auth
|
|
5
|
+
* 2. Active profile with `api_key` set → API Key auth
|
|
6
|
+
* 3. Active account OAuth tokens → Bearer auth (auto-refresh)
|
|
7
|
+
*/
|
|
8
|
+
import { getActiveAccount, readActive, readAuth, readProfile } from "../config/store.js";
|
|
9
|
+
import { ensureFreshAccessToken } from "../auth/oauth.js";
|
|
10
|
+
export const GLOBAL_API_URL = process.env.SOLTI_API_URL_GLOBAL ?? "https://api.solti.run/1";
|
|
11
|
+
/**
|
|
12
|
+
* Resolves credentials per spec §1.1. `apiKeyOverride` corresponds to the
|
|
13
|
+
* global `--api-key` flag (highest priority, together with SOLTI_PROJECT_ID).
|
|
14
|
+
*/
|
|
15
|
+
export async function resolveCredentials(apiKeyOverride) {
|
|
16
|
+
// 1. Explicit flag / environment variables (headless path — no local files).
|
|
17
|
+
const apiKey = apiKeyOverride ?? process.env.SOLTI_API_KEY;
|
|
18
|
+
if (apiKey !== undefined && apiKey !== "") {
|
|
19
|
+
const projectId = process.env.SOLTI_PROJECT_ID;
|
|
20
|
+
return {
|
|
21
|
+
credentials: { kind: "api_key", apiKey, projectId },
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
// 2. Active profile with an api_key set.
|
|
25
|
+
const account = await getActiveAccount();
|
|
26
|
+
if (account !== null) {
|
|
27
|
+
const active = await readActive();
|
|
28
|
+
const profileName = process.env.SOLTI_PROFILE ?? active.active_profile;
|
|
29
|
+
if (profileName !== null && profileName !== undefined) {
|
|
30
|
+
const config = await readProfile(account, profileName);
|
|
31
|
+
if (config !== null && config.api_key !== null && config.api_key !== undefined) {
|
|
32
|
+
return {
|
|
33
|
+
credentials: {
|
|
34
|
+
kind: "api_key",
|
|
35
|
+
apiKey: config.api_key,
|
|
36
|
+
projectId: config.project_id,
|
|
37
|
+
},
|
|
38
|
+
profileName,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// 3. Active account OAuth tokens (+ project binding from the active profile).
|
|
44
|
+
if (account !== null && (await readAuth(account)) !== null) {
|
|
45
|
+
const active = await readActive();
|
|
46
|
+
const profileName = process.env.SOLTI_PROFILE ?? active.active_profile;
|
|
47
|
+
let profileProjectId;
|
|
48
|
+
if (profileName !== null && profileName !== undefined) {
|
|
49
|
+
const config = await readProfile(account, profileName);
|
|
50
|
+
profileProjectId = config?.project_id;
|
|
51
|
+
}
|
|
52
|
+
const projectId = process.env.SOLTI_PROJECT_ID ?? profileProjectId;
|
|
53
|
+
return { credentials: { kind: "oauth", account, projectId } };
|
|
54
|
+
}
|
|
55
|
+
return { credentials: null };
|
|
56
|
+
}
|
|
57
|
+
export function projectBaseUrl(credentials, apiUrlOverride) {
|
|
58
|
+
const projectId = credentials.projectId;
|
|
59
|
+
if (projectId === undefined || projectId === "")
|
|
60
|
+
return null;
|
|
61
|
+
// Precedence: explicit profile override > SOLTI_API_URL env var > global default.
|
|
62
|
+
const override = apiUrlOverride ?? process.env.SOLTI_API_URL;
|
|
63
|
+
if (override !== undefined && override !== null && override !== "") {
|
|
64
|
+
return `${override.replace(/\/$/, "")}/1`;
|
|
65
|
+
}
|
|
66
|
+
// Change 033 D-1: per-project wildcard hosts (<projectId>.api.solti.run) are
|
|
67
|
+
// not deployed; project-scoped requests go to the shared host and are scoped
|
|
68
|
+
// by the X-Solti-Project-Id header (sent in request() below).
|
|
69
|
+
return GLOBAL_API_URL;
|
|
70
|
+
}
|
|
71
|
+
/** Returns the active profile's `api_url` override, if set. */
|
|
72
|
+
async function profileApiUrlOverride() {
|
|
73
|
+
const account = await getActiveAccount();
|
|
74
|
+
if (account === null)
|
|
75
|
+
return null;
|
|
76
|
+
const active = await readActive();
|
|
77
|
+
const profileName = process.env.SOLTI_PROFILE ?? active.active_profile;
|
|
78
|
+
if (profileName === null || profileName === undefined)
|
|
79
|
+
return null;
|
|
80
|
+
const config = await readProfile(account, profileName);
|
|
81
|
+
return config?.api_url ?? null;
|
|
82
|
+
}
|
|
83
|
+
export class ApiError extends Error {
|
|
84
|
+
status;
|
|
85
|
+
payload;
|
|
86
|
+
constructor(status, payload) {
|
|
87
|
+
super(`Solti API error (HTTP ${status})`);
|
|
88
|
+
this.status = status;
|
|
89
|
+
this.payload = payload;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function authHeaders(credentials) {
|
|
93
|
+
if (credentials.kind === "api_key") {
|
|
94
|
+
return { "X-Solti-API-Key": credentials.apiKey };
|
|
95
|
+
}
|
|
96
|
+
const token = await ensureFreshAccessToken(credentials.account);
|
|
97
|
+
return { Authorization: `Bearer ${token}` };
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Performs a request against the Solti API. `path` is relative to the `/1`
|
|
101
|
+
* base (e.g. `jobs`, `account`). Project-scoped requests require a resolved
|
|
102
|
+
* project id (from the environment or the active profile).
|
|
103
|
+
*/
|
|
104
|
+
export async function request(path, options = {}) {
|
|
105
|
+
const target = await resolveCredentials();
|
|
106
|
+
if (target.credentials === null) {
|
|
107
|
+
throw new Error("No credentials found. Run `solti account login`, or set SOLTI_API_KEY and SOLTI_PROJECT_ID.");
|
|
108
|
+
}
|
|
109
|
+
const credentials = target.credentials;
|
|
110
|
+
let baseUrl;
|
|
111
|
+
if (options.global === true) {
|
|
112
|
+
baseUrl = GLOBAL_API_URL;
|
|
113
|
+
if (credentials.kind !== "oauth") {
|
|
114
|
+
throw new Error("Global endpoints (account/organization/project) require OAuth login (`solti account login`).");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
const override = await profileApiUrlOverride();
|
|
119
|
+
const url = projectBaseUrl(credentials, override);
|
|
120
|
+
if (url === null) {
|
|
121
|
+
throw new Error("No active project. Run `solti profile set <name> --project-id <id>` / `solti project use <id>`, or set SOLTI_PROJECT_ID.");
|
|
122
|
+
}
|
|
123
|
+
baseUrl = url;
|
|
124
|
+
}
|
|
125
|
+
const headers = {
|
|
126
|
+
...(await authHeaders(credentials)),
|
|
127
|
+
"Content-Type": "application/json",
|
|
128
|
+
};
|
|
129
|
+
if (options.global !== true && credentials.projectId !== undefined) {
|
|
130
|
+
headers["X-Solti-Project-Id"] = credentials.projectId;
|
|
131
|
+
}
|
|
132
|
+
const method = options.method ?? "GET";
|
|
133
|
+
const isIdempotentRead = method === "GET";
|
|
134
|
+
let attempts = 0;
|
|
135
|
+
let retryAfterMs = 0;
|
|
136
|
+
// Rate-limit friendly behavior (api spec §5): auto-retry idempotent reads.
|
|
137
|
+
while (true) {
|
|
138
|
+
if (retryAfterMs > 0) {
|
|
139
|
+
await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
|
|
140
|
+
}
|
|
141
|
+
attempts += 1;
|
|
142
|
+
const response = await fetch(`${baseUrl}/${path.replace(/^\//, "")}`, {
|
|
143
|
+
method,
|
|
144
|
+
headers,
|
|
145
|
+
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
146
|
+
});
|
|
147
|
+
if (response.status === 429 && isIdempotentRead && attempts <= 2) {
|
|
148
|
+
const retryAfter = Number(response.headers.get("Retry-After") ?? "5");
|
|
149
|
+
retryAfterMs = Math.min(Number.isFinite(retryAfter) ? retryAfter * 1000 : 5000, 30_000);
|
|
150
|
+
console.error(`Rate limited (429). Retrying in ${retryAfterMs / 1000}s...`);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const text = await response.text();
|
|
154
|
+
let payload = null;
|
|
155
|
+
try {
|
|
156
|
+
payload = text === "" ? null : JSON.parse(text);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
payload = text;
|
|
160
|
+
}
|
|
161
|
+
if (!response.ok) {
|
|
162
|
+
throw new ApiError(response.status, payload);
|
|
163
|
+
}
|
|
164
|
+
return payload;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LogTo OAuth 2.0 Authorization Code + PKCE flow for the Solti CLI.
|
|
3
|
+
*
|
|
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.
|
|
19
|
+
*/
|
|
20
|
+
import crypto from "node:crypto";
|
|
21
|
+
import http from "node:http";
|
|
22
|
+
import { deleteAuth, getActiveAccount, listAccounts, readActive, readAuth, writeActive, writeAuth, } from "../config/store.js";
|
|
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";
|
|
25
|
+
export const RESOURCE = process.env.SOLTI_LOGTO_RESOURCE ?? "https://api.solti.run";
|
|
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
|
+
}
|
|
52
|
+
/** Fixed registered loopback port range (spec §1.1 / logto-changes.md §5.1). */
|
|
53
|
+
const CALLBACK_PORTS = [4242, 4243, 4244, 4245];
|
|
54
|
+
const CALLBACK_PATH = "/callback";
|
|
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`);
|
|
61
|
+
if (!response.ok) {
|
|
62
|
+
throw new Error(`Failed to discover LogTo OIDC configuration (HTTP ${response.status})`);
|
|
63
|
+
}
|
|
64
|
+
const discovery = (await response.json());
|
|
65
|
+
discoveryCache.set(issuer, discovery);
|
|
66
|
+
return discovery;
|
|
67
|
+
}
|
|
68
|
+
function base64url(buffer) {
|
|
69
|
+
return buffer.toString("base64url");
|
|
70
|
+
}
|
|
71
|
+
function openBrowser(url) {
|
|
72
|
+
import("node:child_process").then(({ spawn }) => {
|
|
73
|
+
const platform = process.platform;
|
|
74
|
+
const command = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
|
|
75
|
+
const args = platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
76
|
+
try {
|
|
77
|
+
spawn(command, args, { stdio: "ignore", detached: true }).unref();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// Browser auto-open failed — the URL is printed to the terminal anyway.
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** Runs the full Authorization Code + PKCE flow and stores tokens. */
|
|
85
|
+
export async function login(options) {
|
|
86
|
+
const launchBrowser = options?.launchBrowser ?? true;
|
|
87
|
+
const oidc = await discover();
|
|
88
|
+
const codeVerifier = base64url(crypto.randomBytes(64));
|
|
89
|
+
const codeChallenge = base64url(crypto.createHash("sha256").update(codeVerifier).digest());
|
|
90
|
+
const state = base64url(crypto.randomBytes(16));
|
|
91
|
+
// Bind the first free loopback port in the registered range.
|
|
92
|
+
const server = await bindCallbackServer();
|
|
93
|
+
const port = server.address().port;
|
|
94
|
+
const redirectUri = `http://localhost:${port}${CALLBACK_PATH}`;
|
|
95
|
+
const authorizationUrl = new URL(oidc.authorization_endpoint);
|
|
96
|
+
authorizationUrl.searchParams.set("response_type", "code");
|
|
97
|
+
authorizationUrl.searchParams.set("client_id", CLIENT_ID);
|
|
98
|
+
authorizationUrl.searchParams.set("redirect_uri", redirectUri);
|
|
99
|
+
authorizationUrl.searchParams.set("scope", SCOPES);
|
|
100
|
+
authorizationUrl.searchParams.set("resource", RESOURCE);
|
|
101
|
+
authorizationUrl.searchParams.set("code_challenge", codeChallenge);
|
|
102
|
+
authorizationUrl.searchParams.set("code_challenge_method", "S256");
|
|
103
|
+
authorizationUrl.searchParams.set("state", state);
|
|
104
|
+
// LogTo only issues a refresh token when `prompt=consent` is requested
|
|
105
|
+
// (first-party apps skip the visible consent screen).
|
|
106
|
+
authorizationUrl.searchParams.set("prompt", "consent");
|
|
107
|
+
if (launchBrowser) {
|
|
108
|
+
console.log(`Opening browser for sign-in:\n ${authorizationUrl.toString()}\n`);
|
|
109
|
+
openBrowser(authorizationUrl.toString());
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
console.log(`Sign-in URL (open it in a browser to continue):\n ${authorizationUrl.toString()}\n`);
|
|
113
|
+
}
|
|
114
|
+
const code = await waitForCallback(server, state);
|
|
115
|
+
server.close();
|
|
116
|
+
const tokens = (await exchangeCode(oidc, code, redirectUri, codeVerifier));
|
|
117
|
+
// Diagnostics: help identify what LogTo actually granted.
|
|
118
|
+
if (tokens.access_token.split(".").length !== 3) {
|
|
119
|
+
console.error("(warning: access token is opaque, not a JWT — the API resource was not bound to the grant)");
|
|
120
|
+
}
|
|
121
|
+
if (tokens.refresh_token === undefined || tokens.refresh_token === "") {
|
|
122
|
+
console.error("(warning: no refresh token issued)");
|
|
123
|
+
}
|
|
124
|
+
const email = decodeIdTokenEmail(tokens.id_token) ?? (await tryUserinfoEmail(oidc, tokens.access_token));
|
|
125
|
+
if (email === null || email === undefined) {
|
|
126
|
+
throw new Error("Could not determine the account email from the token response.");
|
|
127
|
+
}
|
|
128
|
+
const auth = {
|
|
129
|
+
access_token: tokens.access_token,
|
|
130
|
+
refresh_token: tokens.refresh_token ?? "",
|
|
131
|
+
expires_at: new Date(Date.now() + tokens.expires_in * 1000).toISOString(),
|
|
132
|
+
token_type: tokens.token_type ?? "Bearer",
|
|
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,
|
|
138
|
+
};
|
|
139
|
+
await writeAuth(email, auth);
|
|
140
|
+
// Switch the active account (adds the account if another one was active).
|
|
141
|
+
const active = await readActive();
|
|
142
|
+
await writeActive({ ...active, active_account: email });
|
|
143
|
+
return { email, auth };
|
|
144
|
+
}
|
|
145
|
+
function bindCallbackServer() {
|
|
146
|
+
return new Promise((resolve, reject) => {
|
|
147
|
+
let lastError = null;
|
|
148
|
+
const tryPort = (index) => {
|
|
149
|
+
if (index >= CALLBACK_PORTS.length) {
|
|
150
|
+
reject(new Error(`All callback ports (${CALLBACK_PORTS.join(", ")}) are busy. ` +
|
|
151
|
+
`Free one of them and run \`solti account login\` again.`));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const port = CALLBACK_PORTS[index];
|
|
155
|
+
const server = http.createServer();
|
|
156
|
+
server.once("error", (error) => {
|
|
157
|
+
if (error.code === "EADDRINUSE") {
|
|
158
|
+
lastError = error;
|
|
159
|
+
tryPort(index + 1);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
reject(error);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
server.listen(port, "127.0.0.1", () => {
|
|
166
|
+
resolve(server);
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
tryPort(0);
|
|
170
|
+
void lastError;
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function waitForCallback(server, expectedState) {
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
const timeout = setTimeout(() => {
|
|
176
|
+
reject(new Error("Sign-in timed out waiting for the browser callback (5 minutes)."));
|
|
177
|
+
}, 5 * 60 * 1000);
|
|
178
|
+
server.on("request", (request, response) => {
|
|
179
|
+
const url = new URL(request.url ?? "/", `http://localhost`);
|
|
180
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
181
|
+
response.writeHead(404).end();
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const error = url.searchParams.get("error");
|
|
185
|
+
const code = url.searchParams.get("code");
|
|
186
|
+
const state = url.searchParams.get("state");
|
|
187
|
+
response.writeHead(200, { "Content-Type": "text/html" });
|
|
188
|
+
response.end(`<!doctype html><html><body style="font-family: sans-serif; text-align: center; padding-top: 4rem;">` +
|
|
189
|
+
`<h2>Solti CLI</h2><p>${error ?? "Sign-in complete. You can close this window and return to the terminal."}</p></body></html>`);
|
|
190
|
+
clearTimeout(timeout);
|
|
191
|
+
if (error !== null && error !== undefined && error !== "") {
|
|
192
|
+
reject(new Error(`Sign-in failed: ${error}`));
|
|
193
|
+
}
|
|
194
|
+
else if (state !== expectedState) {
|
|
195
|
+
reject(new Error("Sign-in failed: state mismatch (possible CSRF). Try again."));
|
|
196
|
+
}
|
|
197
|
+
else if (code === null || code === "") {
|
|
198
|
+
reject(new Error("Sign-in failed: missing authorization code."));
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
resolve(code);
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
async function exchangeCode(oidc, code, redirectUri, codeVerifier) {
|
|
207
|
+
const response = await fetch(oidc.token_endpoint, {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
210
|
+
body: new URLSearchParams({
|
|
211
|
+
grant_type: "authorization_code",
|
|
212
|
+
code,
|
|
213
|
+
redirect_uri: redirectUri,
|
|
214
|
+
client_id: CLIENT_ID,
|
|
215
|
+
code_verifier: codeVerifier,
|
|
216
|
+
resource: RESOURCE,
|
|
217
|
+
}),
|
|
218
|
+
});
|
|
219
|
+
if (!response.ok) {
|
|
220
|
+
throw new Error(`Token exchange failed (HTTP ${response.status}): ${await response.text()}`);
|
|
221
|
+
}
|
|
222
|
+
return response.json();
|
|
223
|
+
}
|
|
224
|
+
/** Best-effort email from the id_token JWT claims (email scope). */
|
|
225
|
+
function decodeIdTokenEmail(idToken) {
|
|
226
|
+
if (idToken === undefined)
|
|
227
|
+
return null;
|
|
228
|
+
const parts = idToken.split(".");
|
|
229
|
+
if (parts.length !== 3)
|
|
230
|
+
return null;
|
|
231
|
+
try {
|
|
232
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
233
|
+
return payload.email ?? payload.username ?? null;
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function tryUserinfoEmail(oidc, accessToken) {
|
|
240
|
+
try {
|
|
241
|
+
const userinfo = await fetchUserinfo(oidc, accessToken);
|
|
242
|
+
return userinfo.email ?? userinfo.username ?? null;
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
async function fetchUserinfo(oidc, accessToken) {
|
|
249
|
+
const response = await fetch(oidc.userinfo_endpoint, {
|
|
250
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
251
|
+
});
|
|
252
|
+
if (!response.ok) {
|
|
253
|
+
throw new Error(`Userinfo lookup failed (HTTP ${response.status})`);
|
|
254
|
+
}
|
|
255
|
+
return (await response.json());
|
|
256
|
+
}
|
|
257
|
+
/** Returns a fresh access token for the given account, refreshing if needed. */
|
|
258
|
+
export async function ensureFreshAccessToken(email) {
|
|
259
|
+
const auth = await readAuth(email);
|
|
260
|
+
if (auth === null) {
|
|
261
|
+
throw new Error(`No stored credentials for ${email}. Run \`solti account login\`.`);
|
|
262
|
+
}
|
|
263
|
+
const expiresAt = Date.parse(auth.expires_at);
|
|
264
|
+
const refreshThreshold = Date.now() + 5 * 60 * 1000;
|
|
265
|
+
// An opaque access token is useless against resource-scoped API endpoints —
|
|
266
|
+
// treat it as stale and refresh into a JWT.
|
|
267
|
+
const isJwt = auth.access_token.split(".").length === 3;
|
|
268
|
+
if (Number.isFinite(expiresAt) && expiresAt > refreshThreshold && isJwt) {
|
|
269
|
+
return auth.access_token;
|
|
270
|
+
}
|
|
271
|
+
if (auth.refresh_token === "") {
|
|
272
|
+
throw new Error(`Session for ${email} expired and no refresh token is stored. Run \`solti account login\`.`);
|
|
273
|
+
}
|
|
274
|
+
const { issuer, clientId } = resolveOidc(auth);
|
|
275
|
+
const oidc = await discover(issuer);
|
|
276
|
+
const response = await fetch(oidc.token_endpoint, {
|
|
277
|
+
method: "POST",
|
|
278
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
279
|
+
body: new URLSearchParams({
|
|
280
|
+
grant_type: "refresh_token",
|
|
281
|
+
refresh_token: auth.refresh_token,
|
|
282
|
+
client_id: clientId,
|
|
283
|
+
// LogTo does not auto-reuse the grant's resource (useGrantedResource=false)
|
|
284
|
+
// — the refreshed access token must explicitly request it to stay a JWT.
|
|
285
|
+
resource: RESOURCE,
|
|
286
|
+
}),
|
|
287
|
+
});
|
|
288
|
+
if (!response.ok) {
|
|
289
|
+
throw new Error(`Token refresh failed for ${email} (HTTP ${response.status}). Run \`solti account login\`.`);
|
|
290
|
+
}
|
|
291
|
+
const tokens = (await response.json());
|
|
292
|
+
const updated = {
|
|
293
|
+
...auth,
|
|
294
|
+
access_token: tokens.access_token,
|
|
295
|
+
// LogTo rotates refresh tokens on use — persist the new one.
|
|
296
|
+
refresh_token: tokens.refresh_token ?? auth.refresh_token,
|
|
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,
|
|
301
|
+
};
|
|
302
|
+
await writeAuth(email, updated);
|
|
303
|
+
return updated.access_token;
|
|
304
|
+
}
|
|
305
|
+
/** Best-effort refresh token revocation + local credential deletion. */
|
|
306
|
+
export async function logout(email) {
|
|
307
|
+
const auth = await readAuth(email);
|
|
308
|
+
if (auth !== null && auth.refresh_token !== "") {
|
|
309
|
+
try {
|
|
310
|
+
const { issuer, clientId } = resolveOidc(auth);
|
|
311
|
+
const oidc = await discover(issuer);
|
|
312
|
+
if (oidc.revocation_endpoint !== undefined) {
|
|
313
|
+
await fetch(oidc.revocation_endpoint, {
|
|
314
|
+
method: "POST",
|
|
315
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
316
|
+
body: new URLSearchParams({ token: auth.refresh_token, client_id: clientId }),
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
// Best-effort only; local deletion happens regardless.
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
await deleteAuth(email);
|
|
325
|
+
const active = await readActive();
|
|
326
|
+
if (active.active_account === email) {
|
|
327
|
+
const remaining = (await listAccounts()).filter((name) => name !== email);
|
|
328
|
+
await writeActive({
|
|
329
|
+
...active,
|
|
330
|
+
active_account: remaining[0],
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
/** Returns the active account, or null with guidance already printed. */
|
|
335
|
+
export async function requireActiveAccount() {
|
|
336
|
+
const account = await getActiveAccount();
|
|
337
|
+
if (account === null) {
|
|
338
|
+
console.error("No logged-in account. Run `solti account login` first.");
|
|
339
|
+
process.exit(1);
|
|
340
|
+
}
|
|
341
|
+
return account;
|
|
342
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { getActiveAccount, listAccounts, readActive, readAuth, writeActive, } from "../config/store.js";
|
|
2
|
+
import { ensureFreshAccessToken, login, logout } from "../auth/oauth.js";
|
|
3
|
+
import { request } from "../api/client.js";
|
|
4
|
+
function redact(token) {
|
|
5
|
+
if (token.length <= 12)
|
|
6
|
+
return "***";
|
|
7
|
+
return `${token.slice(0, 8)}…${token.slice(-4)}`;
|
|
8
|
+
}
|
|
9
|
+
export async function accountLogin(options) {
|
|
10
|
+
const { email } = await login(options);
|
|
11
|
+
console.log(`Logged in as ${email}.`);
|
|
12
|
+
}
|
|
13
|
+
export async function accountLogout() {
|
|
14
|
+
const account = await getActiveAccount();
|
|
15
|
+
if (account === null) {
|
|
16
|
+
console.error("No logged-in account.");
|
|
17
|
+
process.exitCode = 1;
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
await logout(account);
|
|
21
|
+
console.log(`Logged out ${account}.`);
|
|
22
|
+
}
|
|
23
|
+
export async function accountList() {
|
|
24
|
+
const accounts = await listAccounts();
|
|
25
|
+
const active = await getActiveAccount();
|
|
26
|
+
if (accounts.length === 0) {
|
|
27
|
+
console.log("No accounts logged in. Run `solti account login`.");
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
for (const account of accounts) {
|
|
31
|
+
const marker = account === active ? "*" : " ";
|
|
32
|
+
console.log(`${marker} ${account}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export async function accountSwitch(email) {
|
|
36
|
+
const accounts = await listAccounts();
|
|
37
|
+
if (!accounts.includes(email)) {
|
|
38
|
+
console.error(`Account ${email} is not logged in locally. Run \`solti account login\` first.`);
|
|
39
|
+
process.exitCode = 1;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const active = await readActive();
|
|
43
|
+
await writeActive({ ...active, active_account: email });
|
|
44
|
+
console.log(`Switched to ${email}.`);
|
|
45
|
+
}
|
|
46
|
+
export async function accountShow(email) {
|
|
47
|
+
const account = email ?? (await getActiveAccount());
|
|
48
|
+
if (account === null || account === undefined) {
|
|
49
|
+
console.error("No logged-in account. Run `solti account login` or pass an email.");
|
|
50
|
+
process.exitCode = 1;
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const auth = await readAuth(account);
|
|
54
|
+
if (auth === null) {
|
|
55
|
+
console.error(`Account ${account} is not logged in locally.`);
|
|
56
|
+
process.exitCode = 1;
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
// Refresh proactively so `expires_at` shown to the user is accurate.
|
|
60
|
+
let tokenPreview;
|
|
61
|
+
let expiresAt;
|
|
62
|
+
try {
|
|
63
|
+
const token = await ensureFreshAccessToken(account);
|
|
64
|
+
tokenPreview = redact(token);
|
|
65
|
+
expiresAt = (await readAuth(account))?.expires_at ?? auth.expires_at;
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
tokenPreview = redact(auth.access_token);
|
|
69
|
+
expiresAt = auth.expires_at;
|
|
70
|
+
console.error(`(warning: ${error.message})`);
|
|
71
|
+
}
|
|
72
|
+
console.log(`Account: ${account}`);
|
|
73
|
+
console.log(`Token: ${tokenPreview} (expires ${expiresAt})`);
|
|
74
|
+
// Organization memberships come from the global account API (WS2).
|
|
75
|
+
try {
|
|
76
|
+
const accountInfo = (await request("account", { global: true }));
|
|
77
|
+
if (accountInfo.organizations !== undefined && accountInfo.organizations.length > 0) {
|
|
78
|
+
console.log("Organizations:");
|
|
79
|
+
for (const organization of accountInfo.organizations) {
|
|
80
|
+
console.log(` - ${organization.name ?? organization.id}${organization.role !== undefined ? ` (${organization.role})` : ""}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
console.log("Organizations: (unavailable — account API not reachable)");
|
|
86
|
+
}
|
|
87
|
+
}
|