@platforma-sdk/pl-cli 0.13.6 → 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.
- package/README.md +208 -0
- package/dist/address.d.ts +6 -0
- package/dist/base_command.d.ts +10 -3
- package/dist/cli.js +649 -230
- package/dist/cli.js.map +1 -1
- package/dist/cmd/login.d.ts +21 -0
- package/dist/cmd/logout.d.ts +7 -0
- package/dist/cmd/session/list.d.ts +6 -0
- package/dist/cmd/session/remove.d.ts +7 -0
- package/dist/cmd/session/select.d.ts +9 -0
- package/dist/cmd-opts.d.ts +8 -3
- package/dist/connection.d.ts +59 -3
- package/dist/index.js +1 -1
- package/dist/instance.d.ts +7 -0
- package/dist/jwt.d.ts +12 -0
- package/dist/lib.d.ts +2 -1
- package/dist/project_ops-CHhJu5k5.js +524 -0
- package/dist/project_ops-CHhJu5k5.js.map +1 -0
- package/dist/prompt.d.ts +5 -0
- package/dist/session_store.d.ts +112 -0
- package/dist/sso.d.ts +30 -0
- package/package.json +3 -3
- package/src/address.ts +15 -0
- package/src/base_command.ts +24 -6
- package/src/cli.ts +74 -3
- package/src/cmd/admin/delete-user.ts +7 -0
- package/src/cmd/login.ts +262 -0
- package/src/cmd/logout.ts +55 -0
- package/src/cmd/session/list.ts +71 -0
- package/src/cmd/session/remove.ts +29 -0
- package/src/cmd/session/select.ts +36 -0
- package/src/cmd-opts.ts +24 -15
- package/src/commands.test.ts +637 -0
- package/src/connection.ts +275 -15
- package/src/instance.ts +19 -0
- package/src/jwt.ts +36 -0
- package/src/lib.ts +12 -0
- package/src/prompt.ts +54 -0
- package/src/session_store.test.ts +237 -0
- package/src/session_store.ts +315 -0
- package/src/sso.test.ts +269 -0
- package/src/sso.ts +336 -0
- package/src/test_backend.ts +151 -0
- package/dist/output-D41Wn0wM.js +0 -229
- package/dist/output-D41Wn0wM.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project_ops-CHhJu5k5.js","names":["redactAddress","address","url","parsePlToken","part","token","payload","err","login","SessionsFileEnv","defaultSessionsPath","fromEnv","join","homedir","isPosix","SessionStore","path","existsSync","parsed","readFileSync","data","instances","instanceId","entry","sessions","session","cur","def","key","rows","removed","release","change","dir","dirname","statSync","mkdirSync","lockPath","deadline","closeSync","openSync","rmSync","tmp","randomBytes","writeFileSync","renameSync","mode","chmodSync","SessionRequiredError","authLogins","authenticatedLogin","pl","lastUsedSession","usedSession","resetUsedSession","probeInstance","unauth","UnauthenticatedPlClient","config","requireInstanceId","OldBackendMessage","createPlConnection","opts","defaultSession","plAddressToConfig","probedId","password","user","authInformation","store","stored","pickSession","renewIfDue","initClient","createAdminPlConnection","PlClient","MinSessionBackendVersion","sessionRefusedMessage","reason","s","issuer","logins","used","expiresAt","refreshAt","inferAuthRefreshTime","jwtToken","isUnauthenticated","isPermissionDenied","initClientOnce","sessionStore","onUpdate","info","outputText","message","outputJson","outputCsv","esc","v","lines","headers","r","formatTable","colWidths","h","i","sep","w","row","cell","formatDate","d","listProjects","tx","projectListRid","entries","f","isNullSignedResourceId","metaStr","createdStr","modifiedStr","ProjectMetaKey","ProjectCreatedTimestamp","ProjectLastModifiedTimestamp","meta","projectId","resourceIdToString","b","a","listProjectIdentities","listProjectIdentitiesInTx","projects","getProjectInfo","kvs","rid","metaKV","kv","createdKV","modifiedKV","schemaKV","SchemaVersionKey","structureKV","ProjectStructureKey","schemaVersion","blockIds","structure","group","block","resolveProject","identifier","getExistingLabelsInTx","labels","deduplicateName","candidate","baseName","existingLabels","renameProject","projectRid","updated","newLabel","deleteProject","field","fieldName","moveProjects","sourceProjectListRid","takenLabels","targetProjectListRid","moved","project","sourceLabel","targetLabel","randomUUID","getProjectListRid","fieldData","ProjectsField","openUserRoot","userRoot","username","isNotFoundError","projectsField","ensureUserProjectList","list","ProjectsResourceType","navigateToUserRoot","userRootRid","projectsFieldData","duplicateProject"],"sources":["../src/address.ts","../src/jwt.ts","../src/session_store.ts","../src/connection.ts","../src/output.ts","../src/project_ops.ts"],"sourcesContent":["/** Returns the Backend address as `scheme://host:port` only. Drops the user name and password,\n * and the query string and fragment, which can hold proxy credentials\n * (`?http-proxy=http://user:password@proxy:3128`). An address without a scheme (`host:6345`)\n * cannot hold credentials and is returned as it is. Use it for every address that pl-cli stores\n * or prints. */\nexport function redactAddress(address: string): string {\n if (address.indexOf(\"://\") === -1) return address;\n let url: URL;\n try {\n url = new URL(address);\n } catch {\n return \"(address that is not a valid URL)\";\n }\n return `${url.protocol}//${url.host}`;\n}\n","/** Claims of a Platforma token that pl-cli reads. The Backend verifies the token; pl-cli only\n * reads the claims to name the login and to know the expiry time. */\nexport interface PlTokenClaims {\n /** The login of the user. */\n login: string;\n /** The instance ID of the Backend that issued the token. */\n issuer?: string;\n /** Expiry time, ms since epoch. */\n expiresAt?: number;\n}\n\n/** Reads the claims of a Platforma JWT without verifying its signature. */\nexport function parsePlToken(token: string): PlTokenClaims {\n const part = token.split(\".\")[1];\n if (part === undefined) throw new Error(\"The Backend returned a token that is not a JWT.\");\n let payload: { sub?: unknown; iss?: unknown; exp?: unknown; user?: { login?: unknown } };\n try {\n payload = JSON.parse(Buffer.from(part, \"base64url\").toString(\"utf8\"));\n } catch (err) {\n throw new Error(\"The Backend returned a token that is not a JWT.\", { cause: err });\n }\n // Current Backends write the login to \"sub\" and copy it to the deprecated \"user.login\". Old\n // Backends write the login only to \"user.login\" and can put a user ID into \"sub\".\n const login =\n typeof payload.user?.login === \"string\" && payload.user.login !== \"\"\n ? payload.user.login\n : typeof payload.sub === \"string\" && payload.sub !== \"\"\n ? payload.sub\n : undefined;\n if (login === undefined) throw new Error(\"The token from the Backend has no login.\");\n return {\n login,\n issuer: typeof payload.iss === \"string\" ? payload.iss : undefined,\n expiresAt: typeof payload.exp === \"number\" ? payload.exp * 1000 : undefined,\n };\n}\n","import { randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\n/** Environment variable that overrides the location of the sessions file. */\nexport const SessionsFileEnv = \"PL_CLI_SESSIONS_FILE\";\n\n/** Kind of the login method that issued a stored token. */\nexport type SessionLoginKind = \"sso\" | \"basic\" | \"token\";\n\n/** One stored sign-in: the token that the Backend issued for one login on one Backend instance.\n * The store never holds a password or a token of the identity provider. */\nexport interface StoredSession {\n /** The login that the token is for. */\n login: string;\n /** The address that was used to sign in. For information only: the instance ID selects the session. */\n address: string;\n /** The Platforma token (JWT) that the Backend issued. */\n token: string;\n /** The login method that issued the token, as the Backend advertises it. */\n loginMethod?: { id: string; kind: SessionLoginKind };\n /** Time of the sign-in, ISO 8601. */\n createdAt: string;\n /** Time of the last token change (sign-in or renewal), ISO 8601. */\n updatedAt: string;\n}\n\ninterface InstanceEntry {\n /** The login of the session that commands use when no login is given. */\n current?: string;\n /** Sessions of this instance, by login. */\n sessions: Record<string, StoredSession>;\n}\n\n/** Content of the sessions file. */\n/** The session that commands without an address use. */\nexport interface DefaultSessionRef {\n instanceId: string;\n login: string;\n}\n\nexport interface SessionsFileData {\n version: 1;\n /** The default session: commands without `--address` use its stored address. It is also the\n * current session of its instance. Absent when no session is the default. */\n default?: DefaultSessionRef;\n /** Sessions by the instance ID that the Backend returns in its ping answer. */\n instances: Record<string, InstanceEntry>;\n}\n\n/** One row of {@link SessionStore.list}. */\nexport interface SessionListEntry {\n instanceId: string;\n /** The current session of its instance: used when the address selects this instance. */\n current: boolean;\n /** The default session: used when no address is given. */\n default: boolean;\n session: StoredSession;\n}\n\n/** Default location of the sessions file: `$PL_CLI_SESSIONS_FILE`, else `~/.platforma/pl-cli.sessions`. */\nexport function defaultSessionsPath(): string {\n const fromEnv = process.env[SessionsFileEnv];\n if (fromEnv !== undefined && fromEnv !== \"\") return fromEnv;\n return join(homedir(), \".platforma\", \"pl-cli.sessions\");\n}\n\nconst isPosix = process.platform !== \"win32\";\n\n/**\n * Stores Backend sessions of pl-cli in one JSON file.\n *\n * Sessions are keyed by the instance ID of the Backend, not by its address: several Backends\n * can answer on the same local address (for example, through SSH tunnels). Each instance can\n * hold sessions of several logins; one of them is current.\n *\n * File protection: on POSIX systems the file has mode 0600 and a directory that the store\n * creates has mode 0700. On Windows, Node.js cannot set these modes; the file is protected by\n * the access rules of the user profile directory, where only the user and administrators can\n * read it by default.\n *\n * Each change takes a lock file (`<path>.lock`), reads the file, changes it and writes it again\n * through a temporary file and a rename. So a reader never sees a partly written file, and two\n * pl-cli processes that change the file at the same time do not lose a change.\n *\n * Instance IDs and logins are keys of objects without a prototype, so a key such as `__proto__`\n * is an ordinary key.\n */\nexport class SessionStore {\n constructor(public readonly path: string = defaultSessionsPath()) {}\n\n /** Reads the file. A missing file gives an empty store. */\n read(): SessionsFileData {\n if (!existsSync(this.path)) return { version: 1, instances: Object.create(null) };\n this.tightenFileMode();\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(this.path, \"utf8\"));\n } catch (err) {\n throw new Error(\n `The sessions file ${this.path} is not valid JSON. Remove it and sign in again.`,\n { cause: err },\n );\n }\n const data = parsed as Partial<SessionsFileData>;\n if (data?.version !== 1 || typeof data.instances !== \"object\" || data.instances === null)\n throw new Error(\n `The sessions file ${this.path} has an unknown format. Remove it and sign in again.`,\n );\n // Copy into objects without a prototype: lookups by key then never find inherited members.\n const instances: Record<string, InstanceEntry> = Object.create(null);\n for (const [instanceId, entry] of Object.entries(data.instances)) {\n const sessions: Record<string, StoredSession> = Object.create(null);\n for (const [login, session] of Object.entries(entry.sessions ?? {}))\n sessions[login] = session;\n instances[instanceId] =\n entry.current === undefined ? { sessions } : { current: entry.current, sessions };\n }\n // A missing, null or malformed entry, or one that names a removed session, means no default.\n const cur: unknown = data.default;\n const def =\n cur !== null &&\n typeof cur === \"object\" &&\n \"instanceId\" in cur &&\n \"login\" in cur &&\n typeof cur.instanceId === \"string\" &&\n typeof cur.login === \"string\" &&\n Object.hasOwn(instances, cur.instanceId) &&\n Object.hasOwn(instances[cur.instanceId].sessions, cur.login)\n ? { instanceId: cur.instanceId, login: cur.login }\n : undefined;\n return def === undefined ? { version: 1, instances } : { version: 1, default: def, instances };\n }\n\n /** Returns the default session (for commands without an address), if any. */\n getDefault(): { instanceId: string; session: StoredSession } | undefined {\n const data = this.read();\n if (data.default === undefined) return undefined;\n const { instanceId, login } = data.default;\n return { instanceId, session: data.instances[instanceId].sessions[login] };\n }\n\n /** Returns the session of `login` on the instance, or the current session when `login` is not given. */\n get(instanceId: string, login?: string): StoredSession | undefined {\n const entry = this.read().instances[instanceId];\n if (entry === undefined) return undefined;\n const key = login ?? entry.current;\n return key === undefined ? undefined : entry.sessions[key];\n }\n\n /** Returns the logins that have sessions on the instance. */\n logins(instanceId: string): string[] {\n return Object.keys(this.read().instances[instanceId]?.sessions ?? {}).sort();\n }\n\n /** Returns all sessions, sorted by instance ID and login. */\n list(): SessionListEntry[] {\n const data = this.read();\n const rows: SessionListEntry[] = [];\n for (const instanceId of Object.keys(data.instances).sort()) {\n const entry = data.instances[instanceId];\n for (const login of Object.keys(entry.sessions).sort())\n rows.push({\n instanceId,\n current: entry.current === login,\n default: data.default?.instanceId === instanceId && data.default.login === login,\n session: entry.sessions[login],\n });\n }\n return rows;\n }\n\n /** Adds the session, or replaces the session of the same login on the instance.\n * The session becomes current on its instance and the default session. */\n put(instanceId: string, session: StoredSession): void {\n this.update((data) => {\n const entry = (data.instances[instanceId] ??= { sessions: Object.create(null) });\n entry.sessions[session.login] = session;\n entry.current = session.login;\n data.default = { instanceId, login: session.login };\n });\n }\n\n /** Replaces the token of an existing session after a renewal. Does nothing if the session is gone. */\n updateToken(instanceId: string, login: string, token: string): void {\n this.update((data) => {\n const session = data.instances[instanceId]?.sessions[login];\n if (session === undefined) return;\n session.token = token;\n session.updatedAt = new Date().toISOString();\n });\n }\n\n /** Makes the session of `login` current on the instance and the default session. */\n select(instanceId: string, login: string): void {\n this.update((data) => {\n const entry = data.instances[instanceId];\n if (entry?.sessions[login] === undefined)\n throw new Error(`No stored session for login \"${login}\" on instance ${instanceId}.`);\n entry.current = login;\n data.default = { instanceId, login };\n });\n }\n\n /** Removes the session of `login`, or the current session when `login` is not given.\n * Returns the removed session. When the current session is removed, the instance has no\n * current session until the next sign-in or `select`. When the default session is removed,\n * there is no default session until then. */\n remove(instanceId: string, login?: string): StoredSession | undefined {\n let removed: StoredSession | undefined;\n this.update((data) => {\n const entry = data.instances[instanceId];\n if (entry === undefined) return;\n const key = login ?? entry.current;\n if (key === undefined) return;\n removed = entry.sessions[key];\n if (removed === undefined) return;\n delete entry.sessions[key];\n if (entry.current === key) delete entry.current;\n if (data.default?.instanceId === instanceId && data.default.login === key)\n delete data.default;\n if (Object.keys(entry.sessions).length === 0) delete data.instances[instanceId];\n });\n return removed;\n }\n\n private update(change: (data: SessionsFileData) => void): void {\n this.prepareDir();\n const release = this.lock();\n try {\n const data = this.read();\n change(data);\n this.write(data);\n } finally {\n release();\n }\n }\n\n /** Creates the directory (mode 0700). Warns when an existing directory is writable by others:\n * they could replace the file. */\n private prepareDir(): void {\n const dir = dirname(this.path);\n if (existsSync(dir)) {\n if (isPosix && (statSync(dir).mode & 0o022) !== 0)\n console.error(\n `warning: the directory ${dir} is writable by other users; they can replace the ` +\n \"sessions file. Run: chmod go-w \" +\n dir,\n );\n return;\n }\n // `mode` applies only to directories that mkdir creates.\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n\n /** Takes the lock file. Waits up to 5 s; removes a lock older than 30 s (a stopped process). */\n private lock(): () => void {\n const lockPath = `${this.path}.lock`;\n const deadline = Date.now() + 5000;\n for (;;) {\n try {\n closeSync(openSync(lockPath, \"wx\", 0o600));\n return () => rmSync(lockPath, { force: true });\n } catch (err) {\n if (!(err instanceof Error && \"code\" in err && err.code === \"EEXIST\")) throw err;\n }\n try {\n if (Date.now() - statSync(lockPath).mtimeMs > 30_000) rmSync(lockPath, { force: true });\n } catch {\n // The other process removed the lock.\n }\n if (Date.now() > deadline)\n throw new Error(\n `The sessions file is locked by another pl-cli process. If no other pl-cli runs, ` +\n `remove ${lockPath}.`,\n );\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);\n }\n }\n\n private write(data: SessionsFileData): void {\n const tmp = `${this.path}.${randomBytes(8).toString(\"hex\")}.tmp`;\n try {\n // \"wx\": never write through a file (or a link) that someone created at this name.\n writeFileSync(tmp, JSON.stringify(data, null, 2) + \"\\n\", { mode: 0o600, flag: \"wx\" });\n renameSync(tmp, this.path);\n } catch (err) {\n rmSync(tmp, { force: true });\n throw err;\n }\n }\n\n /** On POSIX, removes group and other access from a file that has it, and tells the user. */\n private tightenFileMode(): void {\n if (!isPosix) return;\n const mode = statSync(this.path).mode & 0o777;\n if ((mode & 0o077) === 0) return;\n chmodSync(this.path, 0o600);\n console.error(\n `warning: the sessions file ${this.path} had mode ${mode.toString(8)}; changed it to 600.`,\n );\n }\n}\n","import {\n PlClient,\n UnauthenticatedPlClient,\n inferAuthRefreshTime,\n isPermissionDenied,\n isUnauthenticated,\n plAddressToConfig,\n type AuthInformation,\n type PlClientConfig,\n} from \"@milaboratories/pl-client\";\nimport { redactAddress } from \"./address\";\nimport { parsePlToken } from \"./jwt\";\nimport { SessionStore, type StoredSession } from \"./session_store\";\n\nexport interface PlConnectionOptions {\n /** Backend address. Absent: the stored address of the default session (see `pl-cli session\n * select`), which is used only if the Backend there still has the same instance ID. */\n address?: string;\n user?: string;\n password?: string;\n /** Store of sessions. Default: the store at the default path. `null`: do not use stored\n * sessions; the connection then needs credentials (as before stored sessions existed). */\n sessionStore?: SessionStore | null;\n}\n\nexport interface AdminConnectionOptions {\n address: string;\n adminUser: string;\n adminPassword: string;\n}\n\n/** The stored session that a connection uses. */\nexport interface UsedSession {\n instanceId: string;\n login: string;\n}\n\n/** Thrown when a stored session cannot be used. The message tells the user what to do. */\nexport class SessionRequiredError extends Error {\n name = \"SessionRequiredError\";\n}\n\nconst authLogins = new WeakMap<PlClient, string>();\n\n/** The login that the client is signed in as, if it is known. */\nexport function authenticatedLogin(pl: PlClient): string | undefined {\n return authLogins.get(pl);\n}\n\nlet lastUsedSession: UsedSession | undefined;\n\n/** The stored session that the last connection of this process used, if any. */\nexport function usedSession(): UsedSession | undefined {\n return lastUsedSession;\n}\n\n/** Forgets the stored session that the last connection used. Call it before a new command. */\nexport function resetUsedSession(): void {\n lastUsedSession = undefined;\n}\n\n/** Opens an unauthenticated client and returns it with the instance ID from the ping answer.\n * The instance ID is `undefined` for a Backend that does not return one (older than v3.0.4);\n * call {@link requireInstanceId} where a stored session is read or written.\n * The caller must close the client: `await unauth.ll.close()`. */\nexport async function probeInstance(\n config: PlClientConfig | string,\n): Promise<{ unauth: UnauthenticatedPlClient; instanceId: string | undefined }> {\n const unauth = await UnauthenticatedPlClient.build(config);\n const instanceId = unauth.ll.serverInfo.instanceId;\n return { unauth, instanceId: instanceId === \"\" ? undefined : instanceId };\n}\n\n/** Stored sessions are keyed by the instance ID; a Backend without one cannot have them. */\nexport function requireInstanceId(instanceId: string | undefined): string {\n if (instanceId === undefined) throw new SessionRequiredError(OldBackendMessage);\n return instanceId;\n}\n\n/**\n * Creates an authenticated PlClient.\n *\n * Credential precedence (`user` and `password` default to the credentials in the address URL):\n * 1. The Backend requires no authentication: anonymous access.\n * 2. `user` and `password` are both given: sign in with them. Stored sessions are not used.\n * 3. Only `user` is given: the stored session of that login on this Backend instance.\n * 4. Nothing is given: the current stored session of this Backend instance.\n *\n * With `sessionStore: null`, rules 3 and 4 do not apply.\n *\n * Without `address`, the connection goes to the stored address of the default session, and\n * rules 3 and 4 use the instance of that session (rule 4: the default session itself). If the\n * Backend at that address has another instance ID (an SSH tunnel now points elsewhere), the\n * connection stops before it sends a token.\n *\n * The instance comes from the ping answer of the Backend at `address`, so a session follows\n * its Backend, not its address.\n */\nexport async function createPlConnection(opts: PlConnectionOptions): Promise<PlClient> {\n let address = opts.address;\n let defaultSession: { instanceId: string; login: string } | undefined;\n if (address === undefined) {\n if (opts.sessionStore === null)\n throw new Error(\"Give the Backend address: --address or PL_ADDRESS.\");\n const def = (opts.sessionStore ?? new SessionStore()).getDefault();\n if (def === undefined)\n throw new SessionRequiredError(\n \"No Backend address and no default session. Give --address (or PL_ADDRESS), sign in with \" +\n '\"pl-cli login -a <address> --method <id>\", or select a stored session with ' +\n '\"pl-cli session select <login> -a <address>\" (see \"pl-cli session list\").',\n );\n address = def.session.address;\n defaultSession = { instanceId: def.instanceId, login: def.session.login };\n }\n\n const config: PlClientConfig = plAddressToConfig(address);\n const { unauth, instanceId: probedId } = await probeInstance(config);\n if (defaultSession !== undefined && probedId !== defaultSession.instanceId) {\n await unauth.ll.close();\n throw new SessionRequiredError(\n `The default session of \"${defaultSession.login}\" is for instance ` +\n `${defaultSession.instanceId}, but the Backend at ${redactAddress(address)} is instance ` +\n `${probedId ?? \"(no instance ID)\"}. No token was sent. Give --address of the Backend, ` +\n 'or select another session with \"pl-cli session select\".',\n );\n }\n\n const password = opts.password ?? config.password;\n // Without an address, a missing login means the login of the default session.\n const user =\n opts.user ?? config.user ?? (password === undefined ? defaultSession?.login : undefined);\n\n let authInformation: AuthInformation;\n let login: string | undefined;\n let session: UsedSession | undefined;\n let store: SessionStore | undefined;\n try {\n if (!(await unauth.requireAuth())) {\n authInformation = {};\n } else if (user !== undefined && password !== undefined) {\n authInformation = await unauth.login(user, password);\n login = user;\n } else if (password !== undefined) {\n throw new Error(\"--password needs --user (or PL_USER).\");\n } else if (opts.sessionStore === null) {\n throw new Error(\n \"Server requires authentication but no credentials provided. \" +\n \"Use --user/--password flags or PL_USER/PL_PASSWORD env vars.\",\n );\n } else {\n const instanceId = requireInstanceId(probedId);\n store = opts.sessionStore ?? new SessionStore();\n const stored = pickSession(store, instanceId, redactAddress(address), user);\n authInformation = { jwtToken: await renewIfDue(unauth, store, instanceId, stored, config) };\n login = stored.login;\n session = { instanceId, login };\n }\n } finally {\n await unauth.ll.close();\n }\n\n const pl = await initClient(config, authInformation, session, store);\n if (login !== undefined) authLogins.set(pl, login);\n return pl;\n}\n\n/** Creates a PlClient with admin/controller credentials. */\nexport async function createAdminPlConnection(opts: AdminConnectionOptions): Promise<PlClient> {\n const config: PlClientConfig = plAddressToConfig(opts.address);\n\n const unauth = await UnauthenticatedPlClient.build(config);\n let authInformation: AuthInformation;\n try {\n authInformation = await unauth.login(opts.adminUser, opts.adminPassword);\n } finally {\n await unauth.ll.close();\n }\n\n const pl = await PlClient.init(config, { authInformation });\n authLogins.set(pl, opts.adminUser);\n return pl;\n}\n\n/** Minimum Backend version for `pl-cli login` and stored sessions: since this version the\n * Backend writes its instance ID into the `iss` claim of the tokens it issues. */\nexport const MinSessionBackendVersion = \"3.6.0\";\n\n/** Message for a token without `iss`: the Backend is too old for stored sessions. */\nexport const OldBackendMessage =\n `This Backend is older than v${MinSessionBackendVersion}; pl-cli login and stored sessions ` +\n `need v${MinSessionBackendVersion} or newer; use --user/--password per command.`;\n\n/** Message for a Backend that refused or expired a stored session. */\nexport function sessionRefusedMessage(s: UsedSession, reason: \"expired\" | \"refused\"): string {\n const what =\n reason === \"expired\"\n ? `The stored session of \"${s.login}\" on instance ${s.instanceId} has expired.`\n : `The Backend refused the stored session of \"${s.login}\" on instance ${s.instanceId}.`;\n return `${what} Run \"pl-cli login\" to sign in again.`;\n}\n\nfunction pickSession(\n store: SessionStore,\n instanceId: string,\n address: string,\n login: string | undefined,\n): StoredSession {\n const stored = store.get(instanceId, login);\n if (stored !== undefined) {\n // The Backend accepts only tokens that it issued, but do not send a token of another\n // Backend to this one at all.\n const { issuer } = parsePlToken(stored.token);\n if (issuer === undefined) throw new SessionRequiredError(OldBackendMessage);\n if (issuer !== instanceId)\n throw new SessionRequiredError(\n `The stored session of \"${stored.login}\" holds a token of instance ${issuer}, ` +\n `not of instance ${instanceId}. It was not sent. Run \"pl-cli login\" to sign in again.`,\n );\n return stored;\n }\n\n const logins = store.logins(instanceId);\n if (login !== undefined)\n throw new SessionRequiredError(\n `No stored session for \"${login}\" on the Backend at ${address} (instance ${instanceId}). ` +\n `Run \"pl-cli login --user ${login}\", or give a password with --password or PL_PASSWORD.`,\n );\n if (logins.length > 0)\n throw new SessionRequiredError(\n `The Backend at ${address} (instance ${instanceId}) has no current session. ` +\n `Stored logins: ${logins.join(\", \")}. Run \"pl-cli session select <login>\" or \"pl-cli login\".`,\n );\n throw new SessionRequiredError(\n `The Backend at ${address} requires authentication and there is no stored session for ` +\n `its instance ${instanceId}. Run \"pl-cli login\", or give credentials with ` +\n `--user/--password (PL_USER/PL_PASSWORD).`,\n );\n}\n\n/** Returns the token of the session. Renews it first when it is past the renewal time, as the\n * Desktop App does, and saves the new token. */\nasync function renewIfDue(\n unauth: UnauthenticatedPlClient,\n store: SessionStore,\n instanceId: string,\n stored: StoredSession,\n config: PlClientConfig,\n): Promise<string> {\n const used = { instanceId, login: stored.login };\n const { expiresAt } = parsePlToken(stored.token);\n if (expiresAt !== undefined && expiresAt <= Date.now())\n throw new SessionRequiredError(sessionRefusedMessage(used, \"expired\"));\n\n const refreshAt = inferAuthRefreshTime({ jwtToken: stored.token }, config.authMaxRefreshSeconds);\n if (refreshAt === undefined || Date.now() < refreshAt || !unauth.hasCapability(\"auth:v2\"))\n return stored.token;\n\n try {\n const { jwtToken } = await unauth.refreshToken(stored.token);\n if (jwtToken === undefined) return stored.token;\n store.updateToken(instanceId, stored.login, jwtToken);\n return jwtToken;\n } catch (err) {\n if (isUnauthenticated(err))\n throw new SessionRequiredError(sessionRefusedMessage(used, \"refused\"), { cause: err });\n // The role of the session cannot renew tokens, or the call failed: the token is still valid.\n if (!isPermissionDenied(err))\n console.error(`warning: cannot renew the stored session: ${String(err)}`);\n return stored.token;\n }\n}\n\nasync function initClient(\n config: PlClientConfig,\n authInformation: AuthInformation,\n session: UsedSession | undefined,\n sessionStore: SessionStore | undefined,\n): Promise<PlClient> {\n const pl = await initClientOnce(config, authInformation, session, sessionStore);\n // The connection pings again. A different instance ID means that another Backend now answers\n // at the address; the stored token must not be used with it.\n if (session !== undefined && pl.serverInfo.instanceId !== session.instanceId) {\n await pl.close();\n throw new SessionRequiredError(\n `The Backend instance at the address changed from ${session.instanceId} to ` +\n `${pl.serverInfo.instanceId} during the connection. Run the command again.`,\n );\n }\n return pl;\n}\n\nasync function initClientOnce(\n config: PlClientConfig,\n authInformation: AuthInformation,\n session: UsedSession | undefined,\n sessionStore: SessionStore | undefined,\n): Promise<PlClient> {\n lastUsedSession = session;\n const onUpdate =\n session === undefined\n ? undefined\n : (info: AuthInformation) => {\n // A long command can pass the renewal time; keep the token that the client renewed.\n if (info.jwtToken === undefined || sessionStore === undefined) return;\n sessionStore.updateToken(session.instanceId, session.login, info.jwtToken);\n };\n try {\n return await PlClient.init(config, { authInformation, onUpdate });\n } catch (err) {\n if (session !== undefined && isUnauthenticated(err))\n throw new SessionRequiredError(sessionRefusedMessage(session, \"refused\"), { cause: err });\n throw err;\n }\n}\n","export type OutputFormat = \"text\" | \"json\" | \"csv\";\n\n/** Outputs a line of text to stdout. */\nexport function outputText(message: string): void {\n console.log(message);\n}\n\n/** Outputs data as formatted JSON to stdout. */\nexport function outputJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n\n/** Outputs a header row + data rows as RFC-4180-ish CSV to stdout. */\nexport function outputCsv(headers: string[], rows: string[][]): void {\n const esc = (v: string) => (/[\",\\r\\n]/.test(v) ? `\"${v.replace(/\"/g, '\"\"')}\"` : v);\n const lines = [headers, ...rows].map((r) => r.map(esc).join(\",\"));\n console.log(lines.join(\"\\n\"));\n}\n\n/** Formats a table as aligned text columns. */\nexport function formatTable(headers: string[], rows: string[][]): string {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n\n const sep = colWidths.map((w) => \"-\".repeat(w)).join(\" \");\n const headerLine = headers.map((h, i) => h.padEnd(colWidths[i])).join(\" \");\n const dataLines = rows.map((row) =>\n row.map((cell, i) => (cell ?? \"\").padEnd(colWidths[i])).join(\" \"),\n );\n\n return [headerLine, sep, ...dataLines].join(\"\\n\");\n}\n\n/** Formats a Date as a short human-readable string. */\nexport function formatDate(d: Date): string {\n if (d.getTime() === 0) return \"(unknown)\";\n return d\n .toISOString()\n .replace(\"T\", \" \")\n .replace(/\\.\\d+Z$/, \"Z\");\n}\n","import type { PlClient, SignedResourceId, PlTransaction } from \"@milaboratories/pl-client\";\nimport {\n field,\n isNotFoundError,\n isNullSignedResourceId,\n resourceIdToString,\n} from \"@milaboratories/pl-client\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n ProjectMetaKey,\n ProjectCreatedTimestamp,\n ProjectLastModifiedTimestamp,\n SchemaVersionKey,\n ProjectStructureKey,\n ProjectsField,\n ProjectsResourceType,\n duplicateProject,\n} from \"@milaboratories/pl-middle-layer\";\nimport type { ProjectMeta } from \"@milaboratories/pl-middle-layer\";\n\nexport interface ProjectEntry {\n id: string;\n rid: SignedResourceId;\n label: string;\n created: Date;\n lastModified: Date;\n}\n\nexport interface ProjectIdentity {\n /** Project ID (resourceIdToString of resource ID) */\n id: string;\n /** Signed resource ID for use in transactions */\n rid: SignedResourceId;\n /** UUID field name in the project list resource */\n fieldName: string;\n}\n\nexport interface ProjectInfo extends ProjectEntry {\n schemaVersion: string | undefined;\n blockCount: number;\n blockIds: string[];\n}\n\n/** List all projects from a project list resource. */\nexport async function listProjects(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<ProjectEntry[]> {\n return await pl.withReadTx(\"listProjects\", async (tx) => {\n const data = await tx.getResourceData(projectListRid, true);\n const entries: ProjectEntry[] = [];\n\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n\n const [metaStr, createdStr, modifiedStr] = await Promise.all([\n tx.getKValueStringIfExists(f.value, ProjectMetaKey),\n tx.getKValueStringIfExists(f.value, ProjectCreatedTimestamp),\n tx.getKValueStringIfExists(f.value, ProjectLastModifiedTimestamp),\n ]);\n\n const meta: ProjectMeta = metaStr ? JSON.parse(metaStr) : { label: \"(unknown)\" };\n\n const projectId = resourceIdToString(f.value);\n entries.push({\n id: projectId,\n rid: f.value,\n label: meta.label,\n created: createdStr ? new Date(Number(createdStr)) : new Date(0),\n lastModified: modifiedStr ? new Date(Number(modifiedStr)) : new Date(0),\n });\n }\n\n entries.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());\n return entries;\n });\n}\n\n/** A project's identity plus its label — what a whole-root operation needs per project. */\nexport interface ProjectIdentityWithLabel extends ProjectIdentity {\n label: string;\n}\n\n/**\n * Lists every project in a project list with the field name holding it, which\n * {@link listProjects} omits. Whole-root operations (moving a user's projects out before the\n * account is deleted) need that field name to detach each project from its old owner.\n */\nexport async function listProjectIdentities(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<ProjectIdentityWithLabel[]> {\n return await pl.withReadTx(\"listProjectIdentities\", async (tx) => {\n return await listProjectIdentitiesInTx(tx, projectListRid);\n });\n}\n\n/**\n * {@link listProjectIdentities} against a transaction the caller already holds, so a write that\n * acts on the list can read it in the same transaction rather than trusting an earlier snapshot.\n */\nexport async function listProjectIdentitiesInTx(\n tx: PlTransaction,\n projectListRid: SignedResourceId,\n): Promise<ProjectIdentityWithLabel[]> {\n const data = await tx.getResourceData(projectListRid, true);\n const projects: ProjectIdentityWithLabel[] = [];\n\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n const meta: ProjectMeta = metaStr ? JSON.parse(metaStr) : { label: \"(unknown)\" };\n\n projects.push({\n id: resourceIdToString(f.value),\n rid: f.value,\n fieldName: f.name,\n label: meta.label,\n });\n }\n\n return projects;\n}\n\n/** Get detailed info about a project. */\nexport async function getProjectInfo(\n pl: PlClient,\n projectId: string,\n rid: SignedResourceId,\n): Promise<ProjectInfo> {\n return await pl.withReadTx(\"getProjectInfo\", async (tx) => {\n const kvs = await tx.listKeyValuesString(rid);\n\n const metaKV = kvs.find((kv: { key: string }) => kv.key === ProjectMetaKey);\n const createdKV = kvs.find((kv: { key: string }) => kv.key === ProjectCreatedTimestamp);\n const modifiedKV = kvs.find((kv: { key: string }) => kv.key === ProjectLastModifiedTimestamp);\n const schemaKV = kvs.find((kv: { key: string }) => kv.key === SchemaVersionKey);\n const structureKV = kvs.find((kv: { key: string }) => kv.key === ProjectStructureKey);\n\n const meta: ProjectMeta = metaKV ? JSON.parse(metaKV.value) : { label: \"(unknown)\" };\n const schemaVersion = schemaKV ? JSON.parse(schemaKV.value) : undefined;\n\n const blockIds: string[] = [];\n if (structureKV) {\n const structure = JSON.parse(structureKV.value);\n for (const group of structure.groups ?? []) {\n for (const block of group.blocks ?? []) {\n blockIds.push(block.id);\n }\n }\n }\n\n return {\n id: projectId,\n rid: rid,\n label: meta.label,\n created: createdKV ? new Date(Number(createdKV.value)) : new Date(0),\n lastModified: modifiedKV ? new Date(Number(modifiedKV.value)) : new Date(0),\n schemaVersion,\n blockCount: blockIds.length,\n blockIds,\n };\n });\n}\n\n/** Resolve a project identifier (id or label) to its project ID, ResourceId and field name. */\nexport async function resolveProject(\n pl: PlClient,\n projectListRid: SignedResourceId,\n identifier: string,\n): Promise<ProjectIdentity> {\n return await pl.withReadTx(\"resolveProject\", async (tx) => {\n const data = await tx.getResourceData(projectListRid, true);\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const projectId = resourceIdToString(f.value);\n if (projectId === identifier) {\n return { id: projectId, rid: f.value, fieldName: f.name };\n }\n }\n // Fallback: match by label\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n if (metaStr) {\n const meta: ProjectMeta = JSON.parse(metaStr);\n if (meta.label === identifier) {\n return { id: resourceIdToString(f.value), rid: f.value, fieldName: f.name };\n }\n }\n }\n\n throw new Error(`Project \"${identifier}\" not found (searched by id and label).`);\n });\n}\n\n/** Read all project labels within an existing transaction. */\nexport async function getExistingLabelsInTx(\n tx: PlTransaction,\n projectListRid: SignedResourceId,\n): Promise<string[]> {\n const data = await tx.getResourceData(projectListRid, true);\n const labels: string[] = [];\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n if (metaStr) {\n const meta: ProjectMeta = JSON.parse(metaStr);\n labels.push(meta.label);\n }\n }\n return labels;\n}\n\n/** Get all project labels from a project list. */\nexport async function getProjectLabels(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<string[]> {\n return await pl.withReadTx(\"getProjectLabels\", async (tx) => {\n return getExistingLabelsInTx(tx, projectListRid);\n });\n}\n\n/**\n * Deduplicates a project name against existing labels.\n * \"X\" → \"X (Copy)\" → \"X (Copy 2)\" → ...\n */\nexport function deduplicateName(baseName: string, existingLabels: string[]): string {\n let candidate = `${baseName} (Copy)`;\n let i = 2;\n while (existingLabels.includes(candidate)) {\n candidate = `${baseName} (Copy ${i})`;\n i++;\n }\n return candidate;\n}\n\n/** Rename a project (update its label). */\nexport async function renameProject(\n pl: PlClient,\n projectRid: SignedResourceId,\n newLabel: string,\n): Promise<void> {\n await pl.withWriteTx(\"renameProject\", async (tx) => {\n const metaStr = await tx.getKValueString(projectRid, ProjectMetaKey);\n const meta: ProjectMeta = JSON.parse(metaStr);\n const updated: ProjectMeta = { ...meta, label: newLabel };\n tx.setKValue(projectRid, ProjectMetaKey, JSON.stringify(updated));\n tx.setKValue(projectRid, ProjectLastModifiedTimestamp, String(Date.now()));\n await tx.commit();\n });\n}\n\n/** Delete a project from the project list. */\nexport async function deleteProject(\n pl: PlClient,\n projectListRid: SignedResourceId,\n fieldName: string,\n): Promise<void> {\n await pl.withWriteTx(\"deleteProject\", async (tx) => {\n tx.removeField(field(projectListRid, fieldName));\n await tx.commit();\n });\n}\n\n/** One project moved by {@link moveProjects}, as it ended up in the target root. */\nexport interface MovedProject {\n id: string;\n /** Label the project had in the source root. */\n sourceLabel: string;\n /** Label it carries in the target root — differs when the name collided and was deduplicated. */\n targetLabel: string;\n}\n\n/**\n * Re-attaches projects from one user's project list to another's, keeping the same project\n * resources — no copy is made, so nothing is duplicated and no data is rewritten.\n *\n * This works across roots because the backend permits a reference between differently coloured\n * resources when the caller holds write access to both, which admin credentials do. Names that\n * collide in the target are deduplicated the way {@link duplicateProject} callers deduplicate\n * theirs, so a move never silently shadows a project the target user already has.\n *\n * The whole batch is one transaction: either every project lands in the target root, or none\n * moves and both roots are untouched.\n */\nexport async function moveProjects(\n pl: PlClient,\n sourceProjectListRid: SignedResourceId,\n targetProjectListRid: SignedResourceId,\n): Promise<MovedProject[]> {\n return await pl.withWriteTx(\"moveProjects\", async (tx) => {\n // Read here rather than taken from the caller: a list read before an operator answered a\n // confirmation prompt describes the account as it was minutes ago, and a project attached\n // since then would be left on the source root — where the account deletion that follows\n // destroys it. Moving what this transaction sees narrows that to the transaction itself.\n const projects = await listProjectIdentitiesInTx(tx, sourceProjectListRid);\n if (projects.length === 0) return [];\n\n const takenLabels = await getExistingLabelsInTx(tx, targetProjectListRid);\n const moved: MovedProject[] = [];\n\n for (const project of projects) {\n const metaStr = await tx.getKValueString(project.rid, ProjectMetaKey);\n const meta: ProjectMeta = JSON.parse(metaStr);\n const sourceLabel = meta.label;\n\n let targetLabel = sourceLabel;\n if (takenLabels.includes(targetLabel)) {\n targetLabel = deduplicateName(sourceLabel, takenLabels);\n tx.setKValue(project.rid, ProjectMetaKey, JSON.stringify({ ...meta, label: targetLabel }));\n tx.setKValue(project.rid, ProjectLastModifiedTimestamp, String(Date.now()));\n }\n // Reserved even when the label was free, so two source projects with the same name do not\n // both keep it.\n takenLabels.push(targetLabel);\n\n // Attached to the target before being detached from the source: the project keeps a\n // reference throughout, so it is never momentarily unreferenced.\n tx.createField(field(targetProjectListRid, randomUUID()), \"Dynamic\", project.rid);\n tx.removeField(field(sourceProjectListRid, project.fieldName));\n\n moved.push({ id: project.id, sourceLabel, targetLabel });\n }\n\n await tx.commit();\n return moved;\n });\n}\n\n/** Get the project list ResourceId for the connected user. */\nexport async function getProjectListRid(pl: PlClient): Promise<SignedResourceId> {\n return await pl.withReadTx(\"getProjectList\", async (tx) => {\n const fieldData = await tx.getField({\n resourceId: tx.clientRoot,\n fieldName: ProjectsField,\n });\n if (isNullSignedResourceId(fieldData.value)) {\n throw new Error(\"No project list found for this user.\");\n }\n return fieldData.value;\n });\n}\n\n/**\n * Resolves a user's root and, if they have one, their project list.\n *\n * Unlike {@link navigateToUserRoot} a missing project list is not an error here: a user who has\n * never opened the app has a root and no list, and that account is still a legitimate target for\n * whole-account operations. Callers that need a list to write into use\n * {@link ensureUserProjectList}.\n */\nexport async function openUserRoot(\n pl: PlClient,\n username: string,\n): Promise<{ userRoot: SignedResourceId; projectListRid: SignedResourceId | undefined }> {\n let userRoot: SignedResourceId | undefined;\n try {\n userRoot = await pl.getUserRoot({ login: username });\n } catch (e) {\n // The backend reports an unknown login as NOT_FOUND on the root, which reads as a missing\n // resource rather than a missing user. Name the actual problem.\n if (isNotFoundError(e)) {\n throw new Error(`User \"${username}\" not found on this server.`);\n }\n throw e;\n }\n if (userRoot === undefined) {\n throw new Error(`User \"${username}\" not found on this server (no root resource).`);\n }\n\n return await pl.withReadTx(\"openUserRoot\", async (tx) => {\n const projectsField = await tx.getFieldIfExists(field(userRoot, ProjectsField));\n if (projectsField === undefined || isNullSignedResourceId(projectsField.value)) {\n return { userRoot, projectListRid: undefined };\n }\n return { userRoot, projectListRid: projectsField.value };\n });\n}\n\n/**\n * Returns a user's project list, creating an empty one when the root has none — the same lazy\n * creation the middle layer performs for the signed-in user, but against an impersonated root, so\n * projects can be re-homed to a user who has never opened the app.\n */\nexport async function ensureUserProjectList(\n pl: PlClient,\n userRoot: SignedResourceId,\n): Promise<SignedResourceId> {\n return await pl.withWriteTx(\"ensureUserProjectList\", async (tx) => {\n const projectsField = field(userRoot, ProjectsField);\n tx.createField(projectsField, \"Dynamic\");\n const fieldData = await tx.getField(projectsField);\n if (!isNullSignedResourceId(fieldData.value)) {\n await tx.commit();\n return fieldData.value;\n }\n\n const list = tx.createEphemeral(ProjectsResourceType);\n tx.lock(list);\n tx.setField(projectsField, list);\n await tx.commit();\n return await list.globalId;\n });\n}\n\n/**\n * Navigates to a specific user's project list resource ID.\n * Tries ListUserResources first (new backend), falls back to SHA256 named resource lookup.\n */\nexport async function navigateToUserRoot(\n pl: PlClient,\n username: string,\n): Promise<{ userRoot: SignedResourceId; projectListRid: SignedResourceId }> {\n let userRootRid: SignedResourceId | undefined;\n\n userRootRid = await pl.getUserRoot({ login: username });\n if (userRootRid === undefined) {\n throw new Error(`User \"${username}\" not found on this server (no root resource).`);\n }\n\n // Read the projects field from the resolved user root\n return await pl.withReadTx(\"navigateToUserProjects\", async (tx) => {\n const projectsFieldData = await tx.getField({\n resourceId: userRootRid,\n fieldName: ProjectsField,\n });\n\n if (isNullSignedResourceId(projectsFieldData.value)) {\n throw new Error(`User \"${username}\" has no project list.`);\n }\n\n return { userRoot: userRootRid, projectListRid: projectsFieldData.value };\n });\n}\n\n// Re-export duplicateProject from pl-middle-layer for use in commands\nexport { duplicateProject };\n"],"mappings":";;;;;;;AAKA,SAAgBA,EAAc,GAAyB;CACrD,IAAIC,EAAQ,QAAQ,KAAK,MAAM,IAAI,OAAOA;CAC1C,IAAIC;CACJ,IAAI;EACF,IAAM,IAAI,IAAID,CAAO;CACvB,QAAQ;EACN,OAAO;CACT;CACA,OAAO,GAAGC,EAAI,SAAS,IAAIA,EAAI;AACjC;;ACFA,SAAgBC,EAAa,GAA8B;CACzD,IAAMC,IAAOC,EAAM,MAAM,GAAG,CAAC,CAAC;CAC9B,IAAID,MAAS,KAAA,GAAW,MAAU,MAAM,iDAAiD;CACzF,IAAIE;CACJ,IAAI;EACF,IAAU,KAAK,MAAM,OAAO,KAAKF,GAAM,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACtE,SAASG,GAAK;EACZ,MAAU,MAAM,mDAAmD,E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ASkE,GAAeE,CAAI,GAC/B,MAAMpE,EAAG,OAAO,GACT,MAAMoE,EAAK;CACpB,CAAC;AACH;AAMA,eAAsBE,GACpB,GACA,GAC2E;CAC3E,IAAIC;CAGJ,IADA,IAAc,MAAMrI,EAAG,YAAY,EAAE,OAAO8H,EAAS,CAAC,GAClDO,MAAgB,KAAA,GAClB,MAAU,MAAM,SAASP,EAAS,+CAA+C;CAInF,OAAO,MAAM9H,EAAG,WAAW,0BAA0B,OAAO,MAAO;EACjE,IAAMsI,IAAoB,MAAMxE,EAAG,SAAS;GAC1C,YAAYuE;GACZ,WAAWV;EACb,CAAC;EAED,IAAIzD,EAAuBoE,EAAkB,KAAK,GAChD,MAAU,MAAM,SAASR,EAAS,uBAAuB;EAG3D,OAAO;GAAE,UAAUO;GAAa,gBAAgBC,EAAkB;EAAM;CAC1E,CAAC;AACH"}
|
package/dist/prompt.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Reads one line from the terminal. Shows the typed characters unless `hidden` is true.
|
|
2
|
+
* Fails when stdin is not a terminal, so scripts get an error instead of a wait. */
|
|
3
|
+
export declare function promptLine(question: string, opts?: {
|
|
4
|
+
hidden?: boolean;
|
|
5
|
+
}): Promise<string>;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** Environment variable that overrides the location of the sessions file. */
|
|
2
|
+
export declare const SessionsFileEnv = "PL_CLI_SESSIONS_FILE";
|
|
3
|
+
/** Kind of the login method that issued a stored token. */
|
|
4
|
+
export type SessionLoginKind = "sso" | "basic" | "token";
|
|
5
|
+
/** One stored sign-in: the token that the Backend issued for one login on one Backend instance.
|
|
6
|
+
* The store never holds a password or a token of the identity provider. */
|
|
7
|
+
export interface StoredSession {
|
|
8
|
+
/** The login that the token is for. */
|
|
9
|
+
login: string;
|
|
10
|
+
/** The address that was used to sign in. For information only: the instance ID selects the session. */
|
|
11
|
+
address: string;
|
|
12
|
+
/** The Platforma token (JWT) that the Backend issued. */
|
|
13
|
+
token: string;
|
|
14
|
+
/** The login method that issued the token, as the Backend advertises it. */
|
|
15
|
+
loginMethod?: {
|
|
16
|
+
id: string;
|
|
17
|
+
kind: SessionLoginKind;
|
|
18
|
+
};
|
|
19
|
+
/** Time of the sign-in, ISO 8601. */
|
|
20
|
+
createdAt: string;
|
|
21
|
+
/** Time of the last token change (sign-in or renewal), ISO 8601. */
|
|
22
|
+
updatedAt: string;
|
|
23
|
+
}
|
|
24
|
+
interface InstanceEntry {
|
|
25
|
+
/** The login of the session that commands use when no login is given. */
|
|
26
|
+
current?: string;
|
|
27
|
+
/** Sessions of this instance, by login. */
|
|
28
|
+
sessions: Record<string, StoredSession>;
|
|
29
|
+
}
|
|
30
|
+
/** Content of the sessions file. */
|
|
31
|
+
/** The session that commands without an address use. */
|
|
32
|
+
export interface DefaultSessionRef {
|
|
33
|
+
instanceId: string;
|
|
34
|
+
login: string;
|
|
35
|
+
}
|
|
36
|
+
export interface SessionsFileData {
|
|
37
|
+
version: 1;
|
|
38
|
+
/** The default session: commands without `--address` use its stored address. It is also the
|
|
39
|
+
* current session of its instance. Absent when no session is the default. */
|
|
40
|
+
default?: DefaultSessionRef;
|
|
41
|
+
/** Sessions by the instance ID that the Backend returns in its ping answer. */
|
|
42
|
+
instances: Record<string, InstanceEntry>;
|
|
43
|
+
}
|
|
44
|
+
/** One row of {@link SessionStore.list}. */
|
|
45
|
+
export interface SessionListEntry {
|
|
46
|
+
instanceId: string;
|
|
47
|
+
/** The current session of its instance: used when the address selects this instance. */
|
|
48
|
+
current: boolean;
|
|
49
|
+
/** The default session: used when no address is given. */
|
|
50
|
+
default: boolean;
|
|
51
|
+
session: StoredSession;
|
|
52
|
+
}
|
|
53
|
+
/** Default location of the sessions file: `$PL_CLI_SESSIONS_FILE`, else `~/.platforma/pl-cli.sessions`. */
|
|
54
|
+
export declare function defaultSessionsPath(): string;
|
|
55
|
+
/**
|
|
56
|
+
* Stores Backend sessions of pl-cli in one JSON file.
|
|
57
|
+
*
|
|
58
|
+
* Sessions are keyed by the instance ID of the Backend, not by its address: several Backends
|
|
59
|
+
* can answer on the same local address (for example, through SSH tunnels). Each instance can
|
|
60
|
+
* hold sessions of several logins; one of them is current.
|
|
61
|
+
*
|
|
62
|
+
* File protection: on POSIX systems the file has mode 0600 and a directory that the store
|
|
63
|
+
* creates has mode 0700. On Windows, Node.js cannot set these modes; the file is protected by
|
|
64
|
+
* the access rules of the user profile directory, where only the user and administrators can
|
|
65
|
+
* read it by default.
|
|
66
|
+
*
|
|
67
|
+
* Each change takes a lock file (`<path>.lock`), reads the file, changes it and writes it again
|
|
68
|
+
* through a temporary file and a rename. So a reader never sees a partly written file, and two
|
|
69
|
+
* pl-cli processes that change the file at the same time do not lose a change.
|
|
70
|
+
*
|
|
71
|
+
* Instance IDs and logins are keys of objects without a prototype, so a key such as `__proto__`
|
|
72
|
+
* is an ordinary key.
|
|
73
|
+
*/
|
|
74
|
+
export declare class SessionStore {
|
|
75
|
+
readonly path: string;
|
|
76
|
+
constructor(path?: string);
|
|
77
|
+
/** Reads the file. A missing file gives an empty store. */
|
|
78
|
+
read(): SessionsFileData;
|
|
79
|
+
/** Returns the default session (for commands without an address), if any. */
|
|
80
|
+
getDefault(): {
|
|
81
|
+
instanceId: string;
|
|
82
|
+
session: StoredSession;
|
|
83
|
+
} | undefined;
|
|
84
|
+
/** Returns the session of `login` on the instance, or the current session when `login` is not given. */
|
|
85
|
+
get(instanceId: string, login?: string): StoredSession | undefined;
|
|
86
|
+
/** Returns the logins that have sessions on the instance. */
|
|
87
|
+
logins(instanceId: string): string[];
|
|
88
|
+
/** Returns all sessions, sorted by instance ID and login. */
|
|
89
|
+
list(): SessionListEntry[];
|
|
90
|
+
/** Adds the session, or replaces the session of the same login on the instance.
|
|
91
|
+
* The session becomes current on its instance and the default session. */
|
|
92
|
+
put(instanceId: string, session: StoredSession): void;
|
|
93
|
+
/** Replaces the token of an existing session after a renewal. Does nothing if the session is gone. */
|
|
94
|
+
updateToken(instanceId: string, login: string, token: string): void;
|
|
95
|
+
/** Makes the session of `login` current on the instance and the default session. */
|
|
96
|
+
select(instanceId: string, login: string): void;
|
|
97
|
+
/** Removes the session of `login`, or the current session when `login` is not given.
|
|
98
|
+
* Returns the removed session. When the current session is removed, the instance has no
|
|
99
|
+
* current session until the next sign-in or `select`. When the default session is removed,
|
|
100
|
+
* there is no default session until then. */
|
|
101
|
+
remove(instanceId: string, login?: string): StoredSession | undefined;
|
|
102
|
+
private update;
|
|
103
|
+
/** Creates the directory (mode 0700). Warns when an existing directory is writable by others:
|
|
104
|
+
* they could replace the file. */
|
|
105
|
+
private prepareDir;
|
|
106
|
+
/** Takes the lock file. Waits up to 5 s; removes a lock older than 30 s (a stopped process). */
|
|
107
|
+
private lock;
|
|
108
|
+
private write;
|
|
109
|
+
/** On POSIX, removes group and other access from a file that has it, and tells the user. */
|
|
110
|
+
private tightenFileMode;
|
|
111
|
+
}
|
|
112
|
+
export {};
|
package/dist/sso.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { SSOAuthMethod } from '@milaboratories/pl-client';
|
|
2
|
+
export interface RunOidcLoginArgs {
|
|
3
|
+
method: SSOAuthMethod;
|
|
4
|
+
/** One-time nonce from the Backend's BeginSSOLogin. */
|
|
5
|
+
nonce: string;
|
|
6
|
+
/** Client secret from the Backend's BeginSSOLogin. Sent to the identity provider token
|
|
7
|
+
* endpoint when set (confidential clients, for example Google); absent for public clients. */
|
|
8
|
+
clientSecret?: string;
|
|
9
|
+
/** Called with the identity provider URL that the user must open. */
|
|
10
|
+
openUrl: (url: string) => void | Promise<void>;
|
|
11
|
+
/** Stops the flow: closes the loopback listener and cancels the token request. */
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Runs the authorization code flow with PKCE (RFC 7636, S256) for a public client, as the
|
|
16
|
+
* Desktop App does: listens on 127.0.0.1 on the first free redirect port that the Backend
|
|
17
|
+
* advertises, sends the user to the identity provider, receives the code and exchanges it for
|
|
18
|
+
* tokens. Returns the raw token response body. The caller gives this body to the Backend
|
|
19
|
+
* (Login with SSO credentials) and must not keep it: only the Backend reads these tokens.
|
|
20
|
+
*/
|
|
21
|
+
export declare function runOidcLogin(args: RunOidcLoginArgs): Promise<Uint8Array>;
|
|
22
|
+
/** Accepts only `https:` URLs, and `http:` URLs to a loopback host (local test identity
|
|
23
|
+
* providers). Other schemes (`file:`, application schemes) must not reach the browser launcher,
|
|
24
|
+
* and plain HTTP to a remote host would send the code and the PKCE verifier in clear text. */
|
|
25
|
+
export declare function requireSecureUrl(raw: string, what: string): URL;
|
|
26
|
+
/** Removes control characters (terminal escape sequences included) from text that comes from
|
|
27
|
+
* the identity provider, before pl-cli prints it. Keeps line feeds and tabs. */
|
|
28
|
+
export declare function sanitizeForTerminal(text: string): string;
|
|
29
|
+
/** Opens the URL in the default browser. Returns false if no browser command could start. */
|
|
30
|
+
export declare function openInBrowser(url: string): Promise<boolean>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@platforma-sdk/pl-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "CLI for Platforma server state manipulation",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"bin": {
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@milaboratories/pl-client": "3.
|
|
26
|
-
"@milaboratories/pl-middle-layer": "2.8.
|
|
25
|
+
"@milaboratories/pl-client": "3.28.0",
|
|
26
|
+
"@milaboratories/pl-middle-layer": "2.8.8",
|
|
27
27
|
"commander": "^15.0.0"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
package/src/address.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Returns the Backend address as `scheme://host:port` only. Drops the user name and password,
|
|
2
|
+
* and the query string and fragment, which can hold proxy credentials
|
|
3
|
+
* (`?http-proxy=http://user:password@proxy:3128`). An address without a scheme (`host:6345`)
|
|
4
|
+
* cannot hold credentials and is returned as it is. Use it for every address that pl-cli stores
|
|
5
|
+
* or prints. */
|
|
6
|
+
export function redactAddress(address: string): string {
|
|
7
|
+
if (address.indexOf("://") === -1) return address;
|
|
8
|
+
let url: URL;
|
|
9
|
+
try {
|
|
10
|
+
url = new URL(address);
|
|
11
|
+
} catch {
|
|
12
|
+
return "(address that is not a valid URL)";
|
|
13
|
+
}
|
|
14
|
+
return `${url.protocol}//${url.host}`;
|
|
15
|
+
}
|
package/src/base_command.ts
CHANGED
|
@@ -6,22 +6,36 @@ import { getProjectListRid, navigateToUserRoot } from "./project_ops";
|
|
|
6
6
|
* Low-level: get an authenticated PlClient without resolving a project list.
|
|
7
7
|
* Use this for commands that navigate to multiple users (e.g. admin copy-project).
|
|
8
8
|
*
|
|
9
|
+
* Credential precedence: `--admin-user` with `--admin-password` first, then `--user` with
|
|
10
|
+
* `--password`. A login without a password (`--admin-user` or `--user` alone) selects the stored
|
|
11
|
+
* session of that login. With no credentials, the current stored session of the Backend instance
|
|
12
|
+
* is used. Without an address, the default stored session gives the address (not with
|
|
13
|
+
* `--admin-password`). See {@link createPlConnection}.
|
|
14
|
+
*
|
|
9
15
|
* Callers own the returned client and must `await pl.close()` when done.
|
|
10
16
|
*/
|
|
11
17
|
export async function connectClient(flags: {
|
|
12
|
-
address
|
|
18
|
+
address?: string;
|
|
13
19
|
user?: string;
|
|
14
20
|
password?: string;
|
|
15
21
|
adminUser?: string;
|
|
16
22
|
adminPassword?: string;
|
|
17
23
|
}): Promise<PlClient> {
|
|
24
|
+
if (flags.adminPassword && !flags.adminUser) {
|
|
25
|
+
throw new Error("--admin-password needs --admin-user (or PL_ADMIN_USER).");
|
|
26
|
+
}
|
|
18
27
|
if (flags.adminUser && flags.adminPassword) {
|
|
28
|
+
if (flags.address === undefined)
|
|
29
|
+
throw new Error("Give the Backend address (--address or PL_ADDRESS) with admin credentials.");
|
|
19
30
|
return createAdminPlConnection({
|
|
20
31
|
address: flags.address,
|
|
21
32
|
adminUser: flags.adminUser,
|
|
22
33
|
adminPassword: flags.adminPassword,
|
|
23
34
|
});
|
|
24
35
|
}
|
|
36
|
+
if (flags.adminUser) {
|
|
37
|
+
return createPlConnection({ address: flags.address, user: flags.adminUser });
|
|
38
|
+
}
|
|
25
39
|
return createPlConnection({
|
|
26
40
|
address: flags.address,
|
|
27
41
|
user: flags.user,
|
|
@@ -31,13 +45,14 @@ export async function connectClient(flags: {
|
|
|
31
45
|
|
|
32
46
|
/**
|
|
33
47
|
* Connect and resolve the project list for a single user.
|
|
34
|
-
* In admin mode (--
|
|
48
|
+
* In admin mode (--target-user with --admin-user + --admin-password, or with the stored session of
|
|
49
|
+
* an admin user), operates on the target user's data.
|
|
35
50
|
* In user mode, operates on the authenticated user's own data.
|
|
36
51
|
*
|
|
37
52
|
* Callers own the returned client and must `await pl.close()` when done.
|
|
38
53
|
*/
|
|
39
54
|
export async function connect(flags: {
|
|
40
|
-
address
|
|
55
|
+
address?: string;
|
|
41
56
|
user?: string;
|
|
42
57
|
password?: string;
|
|
43
58
|
adminUser?: string;
|
|
@@ -48,9 +63,12 @@ export async function connect(flags: {
|
|
|
48
63
|
const hasAdminPassword = !!flags.adminPassword;
|
|
49
64
|
const hasTarget = !!flags.targetUser;
|
|
50
65
|
|
|
51
|
-
// Validate flag combinations
|
|
52
|
-
|
|
53
|
-
|
|
66
|
+
// Validate flag combinations. --target-user works with admin credentials or with a stored
|
|
67
|
+
// session of an admin user; the Backend checks the role.
|
|
68
|
+
if (hasTarget && !(hasAdminUser && hasAdminPassword) && flags.password !== undefined) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
"--target-user requires --admin-user and --admin-password, or a stored session of an admin user",
|
|
71
|
+
);
|
|
54
72
|
}
|
|
55
73
|
if ((hasAdminUser || hasAdminPassword) && !hasTarget) {
|
|
56
74
|
throw new Error("--admin-user/--admin-password require --target-user for project commands");
|
package/src/cli.ts
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
import { Command } from "commander";
|
|
2
|
+
import { isUnauthenticated } from "@milaboratories/pl-client";
|
|
3
|
+
import {
|
|
4
|
+
SessionRequiredError,
|
|
5
|
+
resetUsedSession,
|
|
6
|
+
sessionRefusedMessage,
|
|
7
|
+
usedSession,
|
|
8
|
+
} from "./connection";
|
|
9
|
+
import loginCommand from "./cmd/login";
|
|
10
|
+
import logoutCommand from "./cmd/logout";
|
|
11
|
+
import sessionListCommand from "./cmd/session/list";
|
|
12
|
+
import sessionSelectCommand from "./cmd/session/select";
|
|
13
|
+
import sessionRemoveCommand from "./cmd/session/remove";
|
|
2
14
|
import projectListCommand from "./cmd/project/list";
|
|
3
15
|
import projectInfoCommand from "./cmd/project/info";
|
|
4
16
|
import projectDuplicateCommand from "./cmd/project/duplicate";
|
|
@@ -14,6 +26,38 @@ import maintenanceSetResourceErrorCommand from "./cmd/maintenance/set-resource-e
|
|
|
14
26
|
export function buildProgram(): Command {
|
|
15
27
|
const program = new Command();
|
|
16
28
|
program.name("pl-cli").description("Platforma command-line client");
|
|
29
|
+
program.addHelpText(
|
|
30
|
+
"after",
|
|
31
|
+
`
|
|
32
|
+
Authentication, in order of precedence:
|
|
33
|
+
1. --admin-user with --admin-password (admin commands), or --user with --password
|
|
34
|
+
(PL_ADMIN_USER/PL_ADMIN_PASSWORD, PL_USER/PL_PASSWORD): sign in with them.
|
|
35
|
+
2. --admin-user or --user without a password: the stored session of that login.
|
|
36
|
+
3. No credentials: the current stored session of the Backend instance.
|
|
37
|
+
Without --address (and PL_ADDRESS), commands use the default session: its stored
|
|
38
|
+
address, if the Backend there still has the same instance ID. "pl-cli login" and
|
|
39
|
+
"pl-cli session select" set the default session.
|
|
40
|
+
Credentials in the address URL (http://user:password@host) count as --user/--password.
|
|
41
|
+
Environment variables count as the flags: a PL_USER or PL_ADMIN_USER in your shell
|
|
42
|
+
selects that login's stored session, and PL_USER with PL_PASSWORD bypasses the
|
|
43
|
+
stored sessions. pl-cli prints a note when it takes credentials from the environment.
|
|
44
|
+
Sign in once with "pl-cli login" (needs Backend v3.6.0 or newer; on older Backends
|
|
45
|
+
give --user/--password with each command). Sessions are keyed by the instance ID from the
|
|
46
|
+
ping answer of the Backend, not by its address. They are stored in
|
|
47
|
+
~/.platforma/pl-cli.sessions (override with PL_CLI_SESSIONS_FILE).`,
|
|
48
|
+
);
|
|
49
|
+
program.hook("preAction", (_program, actionCommand) => noteCredentialsFromEnv(actionCommand));
|
|
50
|
+
|
|
51
|
+
program.addCommand(loginCommand());
|
|
52
|
+
program.addCommand(logoutCommand());
|
|
53
|
+
|
|
54
|
+
const session = new Command("session").description(
|
|
55
|
+
"Manage stored sessions (one file, sessions keyed by Backend instance ID)",
|
|
56
|
+
);
|
|
57
|
+
session.addCommand(sessionListCommand());
|
|
58
|
+
session.addCommand(sessionSelectCommand());
|
|
59
|
+
session.addCommand(sessionRemoveCommand());
|
|
60
|
+
program.addCommand(session);
|
|
17
61
|
|
|
18
62
|
const project = new Command("project").description("Manage projects");
|
|
19
63
|
project.addCommand(projectListCommand());
|
|
@@ -24,7 +68,7 @@ export function buildProgram(): Command {
|
|
|
24
68
|
program.addCommand(project);
|
|
25
69
|
|
|
26
70
|
const admin = new Command("admin").description(
|
|
27
|
-
"Admin operations (requires controller credentials)",
|
|
71
|
+
"Admin operations (requires controller credentials or an admin's stored session)",
|
|
28
72
|
);
|
|
29
73
|
admin.addCommand(adminCopyProjectCommand());
|
|
30
74
|
admin.addCommand(adminUserListCommand());
|
|
@@ -33,7 +77,7 @@ export function buildProgram(): Command {
|
|
|
33
77
|
program.addCommand(admin);
|
|
34
78
|
|
|
35
79
|
const maintenance = new Command("maintenance").description(
|
|
36
|
-
"Low-level server state repair (requires admin/controller credentials)",
|
|
80
|
+
"Low-level server state repair (requires admin/controller credentials or an admin's stored session)",
|
|
37
81
|
);
|
|
38
82
|
maintenance.addCommand(maintenanceListResourcesCommand());
|
|
39
83
|
maintenance.addCommand(maintenanceSetResourceErrorCommand());
|
|
@@ -42,6 +86,33 @@ export function buildProgram(): Command {
|
|
|
42
86
|
return program;
|
|
43
87
|
}
|
|
44
88
|
|
|
89
|
+
const credentialEnv: Record<string, string> = {
|
|
90
|
+
user: "PL_USER",
|
|
91
|
+
password: "PL_PASSWORD",
|
|
92
|
+
adminUser: "PL_ADMIN_USER",
|
|
93
|
+
adminPassword: "PL_ADMIN_PASSWORD",
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** Prints one line when credentials come from environment variables: they change which login
|
|
97
|
+
* a command uses, and the user can forget that they are set. */
|
|
98
|
+
function noteCredentialsFromEnv(cmd: Command): void {
|
|
99
|
+
const fromEnv = Object.entries(credentialEnv)
|
|
100
|
+
.filter(([option]) => cmd.getOptionValueSource(option) === "env")
|
|
101
|
+
.map(([, env]) => env);
|
|
102
|
+
if (fromEnv.length > 0)
|
|
103
|
+
process.stderr.write(`note: using credentials from the environment: ${fromEnv.join(", ")}\n`);
|
|
104
|
+
}
|
|
105
|
+
|
|
45
106
|
export async function run(argv: string[] = process.argv): Promise<void> {
|
|
46
|
-
|
|
107
|
+
resetUsedSession();
|
|
108
|
+
try {
|
|
109
|
+
await buildProgram().parseAsync(argv);
|
|
110
|
+
} catch (err) {
|
|
111
|
+
// A stored token can pass the local expiry check and still be refused later, for example
|
|
112
|
+
// when the session was closed on the Backend. Tell the user to sign in again.
|
|
113
|
+
const session = usedSession();
|
|
114
|
+
if (session !== undefined && !(err instanceof SessionRequiredError) && isUnauthenticated(err))
|
|
115
|
+
throw new Error(sessionRefusedMessage(session, "refused"), { cause: err });
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
47
118
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Command, Option } from "commander";
|
|
2
2
|
import { createInterface } from "node:readline";
|
|
3
3
|
import { connectClient } from "../../base_command";
|
|
4
|
+
import { authenticatedLogin } from "../../connection";
|
|
4
5
|
import { addOptions, GlobalOptions, AdminAuthOptions } from "../../cmd-opts";
|
|
5
6
|
import {
|
|
6
7
|
ensureUserProjectList,
|
|
@@ -52,6 +53,12 @@ export default function adminDeleteUserCommand(): Command {
|
|
|
52
53
|
|
|
53
54
|
const pl = await connectClient(flags);
|
|
54
55
|
try {
|
|
56
|
+
// The same check for a stored session, whose login is known only after connecting.
|
|
57
|
+
if (authenticatedLogin(pl) === user) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`Refusing to delete "${user}" — it is the account this session authenticates as.`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
55
62
|
const source = await openUserRoot(pl, user);
|
|
56
63
|
// No project list means the account never opened the app, so it owns nothing — a state to
|
|
57
64
|
// delete straight through, not to fail on.
|