@platforma-sdk/pl-cli 0.13.5 → 0.14.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.
Files changed (45) hide show
  1. package/README.md +208 -0
  2. package/dist/address.d.ts +6 -0
  3. package/dist/base_command.d.ts +10 -3
  4. package/dist/cli.js +649 -230
  5. package/dist/cli.js.map +1 -1
  6. package/dist/cmd/login.d.ts +21 -0
  7. package/dist/cmd/logout.d.ts +7 -0
  8. package/dist/cmd/session/list.d.ts +6 -0
  9. package/dist/cmd/session/remove.d.ts +7 -0
  10. package/dist/cmd/session/select.d.ts +9 -0
  11. package/dist/cmd-opts.d.ts +8 -3
  12. package/dist/connection.d.ts +59 -3
  13. package/dist/index.js +1 -1
  14. package/dist/instance.d.ts +7 -0
  15. package/dist/jwt.d.ts +12 -0
  16. package/dist/lib.d.ts +2 -1
  17. package/dist/project_ops-CHhJu5k5.js +524 -0
  18. package/dist/project_ops-CHhJu5k5.js.map +1 -0
  19. package/dist/prompt.d.ts +5 -0
  20. package/dist/session_store.d.ts +112 -0
  21. package/dist/sso.d.ts +30 -0
  22. package/package.json +3 -3
  23. package/src/address.ts +15 -0
  24. package/src/base_command.ts +24 -6
  25. package/src/cli.ts +74 -3
  26. package/src/cmd/admin/delete-user.ts +7 -0
  27. package/src/cmd/login.ts +262 -0
  28. package/src/cmd/logout.ts +55 -0
  29. package/src/cmd/session/list.ts +71 -0
  30. package/src/cmd/session/remove.ts +29 -0
  31. package/src/cmd/session/select.ts +36 -0
  32. package/src/cmd-opts.ts +24 -15
  33. package/src/commands.test.ts +637 -0
  34. package/src/connection.ts +275 -15
  35. package/src/instance.ts +19 -0
  36. package/src/jwt.ts +36 -0
  37. package/src/lib.ts +12 -0
  38. package/src/prompt.ts +54 -0
  39. package/src/session_store.test.ts +237 -0
  40. package/src/session_store.ts +315 -0
  41. package/src/sso.test.ts +269 -0
  42. package/src/sso.ts +336 -0
  43. package/src/test_backend.ts +151 -0
  44. package/dist/output-D41Wn0wM.js +0 -229
  45. package/dist/output-D41Wn0wM.js.map +0 -1
package/src/connection.ts CHANGED
@@ -1,15 +1,26 @@
1
1
  import {
2
2
  PlClient,
3
3
  UnauthenticatedPlClient,
4
+ inferAuthRefreshTime,
5
+ isPermissionDenied,
6
+ isUnauthenticated,
4
7
  plAddressToConfig,
5
8
  type AuthInformation,
6
9
  type PlClientConfig,
7
10
  } from "@milaboratories/pl-client";
11
+ import { redactAddress } from "./address";
12
+ import { parsePlToken } from "./jwt";
13
+ import { SessionStore, type StoredSession } from "./session_store";
8
14
 
9
15
  export interface PlConnectionOptions {
10
- address: string;
16
+ /** Backend address. Absent: the stored address of the default session (see `pl-cli session
17
+ * select`), which is used only if the Backend there still has the same instance ID. */
18
+ address?: string;
11
19
  user?: string;
12
20
  password?: string;
21
+ /** Store of sessions. Default: the store at the default path. `null`: do not use stored
22
+ * sessions; the connection then needs credentials (as before stored sessions existed). */
23
+ sessionStore?: SessionStore | null;
13
24
  }
14
25
 
15
26
  export interface AdminConnectionOptions {
@@ -18,29 +29,139 @@ export interface AdminConnectionOptions {
18
29
  adminPassword: string;
19
30
  }
20
31
 
21
- /** Creates an authenticated PlClient from address + credentials. */
22
- export async function createPlConnection(opts: PlConnectionOptions): Promise<PlClient> {
23
- const config: PlClientConfig = plAddressToConfig(opts.address);
32
+ /** The stored session that a connection uses. */
33
+ export interface UsedSession {
34
+ instanceId: string;
35
+ login: string;
36
+ }
37
+
38
+ /** Thrown when a stored session cannot be used. The message tells the user what to do. */
39
+ export class SessionRequiredError extends Error {
40
+ name = "SessionRequiredError";
41
+ }
42
+
43
+ const authLogins = new WeakMap<PlClient, string>();
44
+
45
+ /** The login that the client is signed in as, if it is known. */
46
+ export function authenticatedLogin(pl: PlClient): string | undefined {
47
+ return authLogins.get(pl);
48
+ }
49
+
50
+ let lastUsedSession: UsedSession | undefined;
51
+
52
+ /** The stored session that the last connection of this process used, if any. */
53
+ export function usedSession(): UsedSession | undefined {
54
+ return lastUsedSession;
55
+ }
24
56
 
25
- if (opts.user !== undefined) config.user = opts.user;
26
- if (opts.password !== undefined) config.password = opts.password;
57
+ /** Forgets the stored session that the last connection used. Call it before a new command. */
58
+ export function resetUsedSession(): void {
59
+ lastUsedSession = undefined;
60
+ }
27
61
 
62
+ /** Opens an unauthenticated client and returns it with the instance ID from the ping answer.
63
+ * The instance ID is `undefined` for a Backend that does not return one (older than v3.0.4);
64
+ * call {@link requireInstanceId} where a stored session is read or written.
65
+ * The caller must close the client: `await unauth.ll.close()`. */
66
+ export async function probeInstance(
67
+ config: PlClientConfig | string,
68
+ ): Promise<{ unauth: UnauthenticatedPlClient; instanceId: string | undefined }> {
28
69
  const unauth = await UnauthenticatedPlClient.build(config);
29
- let authInformation: AuthInformation;
70
+ const instanceId = unauth.ll.serverInfo.instanceId;
71
+ return { unauth, instanceId: instanceId === "" ? undefined : instanceId };
72
+ }
73
+
74
+ /** Stored sessions are keyed by the instance ID; a Backend without one cannot have them. */
75
+ export function requireInstanceId(instanceId: string | undefined): string {
76
+ if (instanceId === undefined) throw new SessionRequiredError(OldBackendMessage);
77
+ return instanceId;
78
+ }
79
+
80
+ /**
81
+ * Creates an authenticated PlClient.
82
+ *
83
+ * Credential precedence (`user` and `password` default to the credentials in the address URL):
84
+ * 1. The Backend requires no authentication: anonymous access.
85
+ * 2. `user` and `password` are both given: sign in with them. Stored sessions are not used.
86
+ * 3. Only `user` is given: the stored session of that login on this Backend instance.
87
+ * 4. Nothing is given: the current stored session of this Backend instance.
88
+ *
89
+ * With `sessionStore: null`, rules 3 and 4 do not apply.
90
+ *
91
+ * Without `address`, the connection goes to the stored address of the default session, and
92
+ * rules 3 and 4 use the instance of that session (rule 4: the default session itself). If the
93
+ * Backend at that address has another instance ID (an SSH tunnel now points elsewhere), the
94
+ * connection stops before it sends a token.
95
+ *
96
+ * The instance comes from the ping answer of the Backend at `address`, so a session follows
97
+ * its Backend, not its address.
98
+ */
99
+ export async function createPlConnection(opts: PlConnectionOptions): Promise<PlClient> {
100
+ let address = opts.address;
101
+ let defaultSession: { instanceId: string; login: string } | undefined;
102
+ if (address === undefined) {
103
+ if (opts.sessionStore === null)
104
+ throw new Error("Give the Backend address: --address or PL_ADDRESS.");
105
+ const def = (opts.sessionStore ?? new SessionStore()).getDefault();
106
+ if (def === undefined)
107
+ throw new SessionRequiredError(
108
+ "No Backend address and no default session. Give --address (or PL_ADDRESS), sign in with " +
109
+ '"pl-cli login -a <address> --method <id>", or select a stored session with ' +
110
+ '"pl-cli session select <login> -a <address>" (see "pl-cli session list").',
111
+ );
112
+ address = def.session.address;
113
+ defaultSession = { instanceId: def.instanceId, login: def.session.login };
114
+ }
115
+
116
+ const config: PlClientConfig = plAddressToConfig(address);
117
+ const { unauth, instanceId: probedId } = await probeInstance(config);
118
+ if (defaultSession !== undefined && probedId !== defaultSession.instanceId) {
119
+ await unauth.ll.close();
120
+ throw new SessionRequiredError(
121
+ `The default session of "${defaultSession.login}" is for instance ` +
122
+ `${defaultSession.instanceId}, but the Backend at ${redactAddress(address)} is instance ` +
123
+ `${probedId ?? "(no instance ID)"}. No token was sent. Give --address of the Backend, ` +
124
+ 'or select another session with "pl-cli session select".',
125
+ );
126
+ }
127
+
128
+ const password = opts.password ?? config.password;
129
+ // Without an address, a missing login means the login of the default session.
130
+ const user =
131
+ opts.user ?? config.user ?? (password === undefined ? defaultSession?.login : undefined);
30
132
 
31
- if (await unauth.requireAuth()) {
32
- if (config.user === undefined || config.password === undefined) {
133
+ let authInformation: AuthInformation;
134
+ let login: string | undefined;
135
+ let session: UsedSession | undefined;
136
+ let store: SessionStore | undefined;
137
+ try {
138
+ if (!(await unauth.requireAuth())) {
139
+ authInformation = {};
140
+ } else if (user !== undefined && password !== undefined) {
141
+ authInformation = await unauth.login(user, password);
142
+ login = user;
143
+ } else if (password !== undefined) {
144
+ throw new Error("--password needs --user (or PL_USER).");
145
+ } else if (opts.sessionStore === null) {
33
146
  throw new Error(
34
147
  "Server requires authentication but no credentials provided. " +
35
148
  "Use --user/--password flags or PL_USER/PL_PASSWORD env vars.",
36
149
  );
150
+ } else {
151
+ const instanceId = requireInstanceId(probedId);
152
+ store = opts.sessionStore ?? new SessionStore();
153
+ const stored = pickSession(store, instanceId, redactAddress(address), user);
154
+ authInformation = { jwtToken: await renewIfDue(unauth, store, instanceId, stored, config) };
155
+ login = stored.login;
156
+ session = { instanceId, login };
37
157
  }
38
- authInformation = await unauth.login(config.user, config.password);
39
- } else {
40
- authInformation = {};
158
+ } finally {
159
+ await unauth.ll.close();
41
160
  }
42
161
 
43
- return await PlClient.init(config, { authInformation });
162
+ const pl = await initClient(config, authInformation, session, store);
163
+ if (login !== undefined) authLogins.set(pl, login);
164
+ return pl;
44
165
  }
45
166
 
46
167
  /** Creates a PlClient with admin/controller credentials. */
@@ -48,7 +169,146 @@ export async function createAdminPlConnection(opts: AdminConnectionOptions): Pro
48
169
  const config: PlClientConfig = plAddressToConfig(opts.address);
49
170
 
50
171
  const unauth = await UnauthenticatedPlClient.build(config);
51
- const authInformation: AuthInformation = await unauth.login(opts.adminUser, opts.adminPassword);
172
+ let authInformation: AuthInformation;
173
+ try {
174
+ authInformation = await unauth.login(opts.adminUser, opts.adminPassword);
175
+ } finally {
176
+ await unauth.ll.close();
177
+ }
178
+
179
+ const pl = await PlClient.init(config, { authInformation });
180
+ authLogins.set(pl, opts.adminUser);
181
+ return pl;
182
+ }
183
+
184
+ /** Minimum Backend version for `pl-cli login` and stored sessions: since this version the
185
+ * Backend writes its instance ID into the `iss` claim of the tokens it issues. */
186
+ export const MinSessionBackendVersion = "3.6.0";
187
+
188
+ /** Message for a token without `iss`: the Backend is too old for stored sessions. */
189
+ export const OldBackendMessage =
190
+ `This Backend is older than v${MinSessionBackendVersion}; pl-cli login and stored sessions ` +
191
+ `need v${MinSessionBackendVersion} or newer; use --user/--password per command.`;
192
+
193
+ /** Message for a Backend that refused or expired a stored session. */
194
+ export function sessionRefusedMessage(s: UsedSession, reason: "expired" | "refused"): string {
195
+ const what =
196
+ reason === "expired"
197
+ ? `The stored session of "${s.login}" on instance ${s.instanceId} has expired.`
198
+ : `The Backend refused the stored session of "${s.login}" on instance ${s.instanceId}.`;
199
+ return `${what} Run "pl-cli login" to sign in again.`;
200
+ }
201
+
202
+ function pickSession(
203
+ store: SessionStore,
204
+ instanceId: string,
205
+ address: string,
206
+ login: string | undefined,
207
+ ): StoredSession {
208
+ const stored = store.get(instanceId, login);
209
+ if (stored !== undefined) {
210
+ // The Backend accepts only tokens that it issued, but do not send a token of another
211
+ // Backend to this one at all.
212
+ const { issuer } = parsePlToken(stored.token);
213
+ if (issuer === undefined) throw new SessionRequiredError(OldBackendMessage);
214
+ if (issuer !== instanceId)
215
+ throw new SessionRequiredError(
216
+ `The stored session of "${stored.login}" holds a token of instance ${issuer}, ` +
217
+ `not of instance ${instanceId}. It was not sent. Run "pl-cli login" to sign in again.`,
218
+ );
219
+ return stored;
220
+ }
52
221
 
53
- return await PlClient.init(config, { authInformation });
222
+ const logins = store.logins(instanceId);
223
+ if (login !== undefined)
224
+ throw new SessionRequiredError(
225
+ `No stored session for "${login}" on the Backend at ${address} (instance ${instanceId}). ` +
226
+ `Run "pl-cli login --user ${login}", or give a password with --password or PL_PASSWORD.`,
227
+ );
228
+ if (logins.length > 0)
229
+ throw new SessionRequiredError(
230
+ `The Backend at ${address} (instance ${instanceId}) has no current session. ` +
231
+ `Stored logins: ${logins.join(", ")}. Run "pl-cli session select <login>" or "pl-cli login".`,
232
+ );
233
+ throw new SessionRequiredError(
234
+ `The Backend at ${address} requires authentication and there is no stored session for ` +
235
+ `its instance ${instanceId}. Run "pl-cli login", or give credentials with ` +
236
+ `--user/--password (PL_USER/PL_PASSWORD).`,
237
+ );
238
+ }
239
+
240
+ /** Returns the token of the session. Renews it first when it is past the renewal time, as the
241
+ * Desktop App does, and saves the new token. */
242
+ async function renewIfDue(
243
+ unauth: UnauthenticatedPlClient,
244
+ store: SessionStore,
245
+ instanceId: string,
246
+ stored: StoredSession,
247
+ config: PlClientConfig,
248
+ ): Promise<string> {
249
+ const used = { instanceId, login: stored.login };
250
+ const { expiresAt } = parsePlToken(stored.token);
251
+ if (expiresAt !== undefined && expiresAt <= Date.now())
252
+ throw new SessionRequiredError(sessionRefusedMessage(used, "expired"));
253
+
254
+ const refreshAt = inferAuthRefreshTime({ jwtToken: stored.token }, config.authMaxRefreshSeconds);
255
+ if (refreshAt === undefined || Date.now() < refreshAt || !unauth.hasCapability("auth:v2"))
256
+ return stored.token;
257
+
258
+ try {
259
+ const { jwtToken } = await unauth.refreshToken(stored.token);
260
+ if (jwtToken === undefined) return stored.token;
261
+ store.updateToken(instanceId, stored.login, jwtToken);
262
+ return jwtToken;
263
+ } catch (err) {
264
+ if (isUnauthenticated(err))
265
+ throw new SessionRequiredError(sessionRefusedMessage(used, "refused"), { cause: err });
266
+ // The role of the session cannot renew tokens, or the call failed: the token is still valid.
267
+ if (!isPermissionDenied(err))
268
+ console.error(`warning: cannot renew the stored session: ${String(err)}`);
269
+ return stored.token;
270
+ }
271
+ }
272
+
273
+ async function initClient(
274
+ config: PlClientConfig,
275
+ authInformation: AuthInformation,
276
+ session: UsedSession | undefined,
277
+ sessionStore: SessionStore | undefined,
278
+ ): Promise<PlClient> {
279
+ const pl = await initClientOnce(config, authInformation, session, sessionStore);
280
+ // The connection pings again. A different instance ID means that another Backend now answers
281
+ // at the address; the stored token must not be used with it.
282
+ if (session !== undefined && pl.serverInfo.instanceId !== session.instanceId) {
283
+ await pl.close();
284
+ throw new SessionRequiredError(
285
+ `The Backend instance at the address changed from ${session.instanceId} to ` +
286
+ `${pl.serverInfo.instanceId} during the connection. Run the command again.`,
287
+ );
288
+ }
289
+ return pl;
290
+ }
291
+
292
+ async function initClientOnce(
293
+ config: PlClientConfig,
294
+ authInformation: AuthInformation,
295
+ session: UsedSession | undefined,
296
+ sessionStore: SessionStore | undefined,
297
+ ): Promise<PlClient> {
298
+ lastUsedSession = session;
299
+ const onUpdate =
300
+ session === undefined
301
+ ? undefined
302
+ : (info: AuthInformation) => {
303
+ // A long command can pass the renewal time; keep the token that the client renewed.
304
+ if (info.jwtToken === undefined || sessionStore === undefined) return;
305
+ sessionStore.updateToken(session.instanceId, session.login, info.jwtToken);
306
+ };
307
+ try {
308
+ return await PlClient.init(config, { authInformation, onUpdate });
309
+ } catch (err) {
310
+ if (session !== undefined && isUnauthenticated(err))
311
+ throw new SessionRequiredError(sessionRefusedMessage(session, "refused"), { cause: err });
312
+ throw err;
313
+ }
54
314
  }
@@ -0,0 +1,19 @@
1
+ import { plAddressToConfig } from "@milaboratories/pl-client";
2
+ import { probeInstance, requireInstanceId } from "./connection";
3
+
4
+ /** Returns the instance ID of the Backend at `address`, from its ping answer. */
5
+ export async function instanceIdOf(address: string): Promise<string> {
6
+ const { unauth, instanceId } = await probeInstance(plAddressToConfig(address));
7
+ await unauth.ll.close();
8
+ return requireInstanceId(instanceId);
9
+ }
10
+
11
+ /** Returns `instance` when given, else the instance ID of the Backend at `address`. */
12
+ export async function resolveInstance(flags: {
13
+ instance?: string;
14
+ address?: string;
15
+ }): Promise<string> {
16
+ if (flags.instance !== undefined) return flags.instance;
17
+ if (flags.address !== undefined) return await instanceIdOf(flags.address);
18
+ throw new Error("Give --instance <id>, or --address (or PL_ADDRESS) of a running Backend.");
19
+ }
package/src/jwt.ts ADDED
@@ -0,0 +1,36 @@
1
+ /** Claims of a Platforma token that pl-cli reads. The Backend verifies the token; pl-cli only
2
+ * reads the claims to name the login and to know the expiry time. */
3
+ export interface PlTokenClaims {
4
+ /** The login of the user. */
5
+ login: string;
6
+ /** The instance ID of the Backend that issued the token. */
7
+ issuer?: string;
8
+ /** Expiry time, ms since epoch. */
9
+ expiresAt?: number;
10
+ }
11
+
12
+ /** Reads the claims of a Platforma JWT without verifying its signature. */
13
+ export function parsePlToken(token: string): PlTokenClaims {
14
+ const part = token.split(".")[1];
15
+ if (part === undefined) throw new Error("The Backend returned a token that is not a JWT.");
16
+ let payload: { sub?: unknown; iss?: unknown; exp?: unknown; user?: { login?: unknown } };
17
+ try {
18
+ payload = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
19
+ } catch (err) {
20
+ throw new Error("The Backend returned a token that is not a JWT.", { cause: err });
21
+ }
22
+ // Current Backends write the login to "sub" and copy it to the deprecated "user.login". Old
23
+ // Backends write the login only to "user.login" and can put a user ID into "sub".
24
+ const login =
25
+ typeof payload.user?.login === "string" && payload.user.login !== ""
26
+ ? payload.user.login
27
+ : typeof payload.sub === "string" && payload.sub !== ""
28
+ ? payload.sub
29
+ : undefined;
30
+ if (login === undefined) throw new Error("The token from the Backend has no login.");
31
+ return {
32
+ login,
33
+ issuer: typeof payload.iss === "string" ? payload.iss : undefined,
34
+ expiresAt: typeof payload.exp === "number" ? payload.exp * 1000 : undefined,
35
+ };
36
+ }
package/src/lib.ts CHANGED
@@ -3,7 +3,19 @@ export {
3
3
  createAdminPlConnection,
4
4
  type PlConnectionOptions,
5
5
  type AdminConnectionOptions,
6
+ type UsedSession,
7
+ SessionRequiredError,
8
+ authenticatedLogin,
6
9
  } from "./connection";
10
+ export {
11
+ SessionStore,
12
+ defaultSessionsPath,
13
+ SessionsFileEnv,
14
+ type StoredSession,
15
+ type SessionsFileData,
16
+ type SessionListEntry,
17
+ type SessionLoginKind,
18
+ } from "./session_store";
7
19
  export {
8
20
  listProjects,
9
21
  getProjectInfo,
package/src/prompt.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { createInterface } from "node:readline";
2
+
3
+ /** Reads one line from the terminal. Shows the typed characters unless `hidden` is true.
4
+ * Fails when stdin is not a terminal, so scripts get an error instead of a wait. */
5
+ export async function promptLine(
6
+ question: string,
7
+ opts: { hidden?: boolean } = {},
8
+ ): Promise<string> {
9
+ const input = process.stdin;
10
+ const output = process.stderr;
11
+ if (!input.isTTY)
12
+ throw new Error(`Cannot ask for input: stdin is not a terminal. (${question.trim()})`);
13
+
14
+ if (!opts.hidden) {
15
+ const rl = createInterface({ input, output, terminal: true });
16
+ try {
17
+ return await new Promise<string>((resolve) => rl.question(question, resolve));
18
+ } finally {
19
+ rl.close();
20
+ }
21
+ }
22
+
23
+ output.write(question);
24
+ input.setRawMode(true);
25
+ input.resume();
26
+ input.setEncoding("utf8");
27
+ try {
28
+ return await new Promise<string>((resolve, reject) => {
29
+ let value = "";
30
+ const onData = (chunk: string) => {
31
+ for (const ch of chunk) {
32
+ if (ch === "\r" || ch === "\n" || ch === "\u0004") {
33
+ input.removeListener("data", onData);
34
+ output.write("\n");
35
+ resolve(value);
36
+ return;
37
+ }
38
+ if (ch === "\u0003") {
39
+ input.removeListener("data", onData);
40
+ output.write("\n");
41
+ reject(new Error("Cancelled."));
42
+ return;
43
+ }
44
+ if (ch === "\u007f" || ch === "\b") value = value.slice(0, -1);
45
+ else value += ch;
46
+ }
47
+ };
48
+ input.on("data", onData);
49
+ });
50
+ } finally {
51
+ input.setRawMode(false);
52
+ input.pause();
53
+ }
54
+ }