@platforma-sdk/pl-cli 0.13.6 → 0.14.1

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/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":["openUserRoot","outputText","createAdminPlConnection","duplicateProject","getProjectInfo","getProjectListRid","navigateToUserRoot","moveProjects","outputJson","listProjects","formatTable","deduplicateName","outputCsv","deleteProject","formatDate","getExistingLabelsInTx","createPlConnection","resolveProject","connectClient","flags","connect","hasAdminUser","hasAdminPassword","hasTarget","pl","projectListRid","addOptions","optionGroups","group","opt","cmd","AddressOptions","Option","GlobalOptions","allowedFormats","formatDefault","UserAuthOptions","AdminAuthOptions","AdminTargetOptions","projectListCommand","Command","projects","p","resourceIdToString","projectInfoCommand","project","info","id","rid","bid","projectDuplicateCommand","sourceRid","newId","randomUUID","result","sourceMetaStr","tx","ProjectMetaKey","sourceLabel","existingLabels","newLabel","newPrj","field","projectResourceId","projectRenameCommand","renameProject","projectDeleteCommand","rl","createInterface","resolve","fieldName","adminCopyProjectCommand","targetUser","source","target","prjResourceId","adminUserListCommand","users","err","isPermissionDenied","logins","u","l","adminDeleteUserCommand","user","listProjectIdentities","confirmDeletion","moved","targetList","ensureUserProjectList","remaining","report","renderResult","assertProjectsAccountedFor","approvedIds","approved","unapproved","fate","lines","movedTo","adminInstanceStatsCommand","context","InstanceStatsContextTypeName","kvs","parseInstanceStats","parseResourceId","str","raw","asSignedResourceId","resourceIdFromString","isLocalResourceId","createSignedResourceId","maintenanceListResourcesCommand","parseResourceTypeArg","parseNonNegativeInt","resources","list","resource","line","toJson","kv","once","r","resourceTypeToString","optionalIdToString","decodeBytes","withFields","fieldToJson","f","isNotNullSignedResourceId","text","bytes","sep","value","InvalidArgumentError","resourceType","n","DefaultErrorMessage","maintenanceSetResourceErrorCommand","ids","rawIds","found","missing","targets","skipped","error","buildProgram","program","admin","maintenance","run","argv"],"sources":["../src/base_command.ts","../src/cmd-opts.ts","../src/cmd/project/list.ts","../src/cmd/project/info.ts","../src/cmd/project/duplicate.ts","../src/cmd/project/rename.ts","../src/cmd/project/delete.ts","../src/cmd/admin/copy-project.ts","../src/cmd/admin/user-list.ts","../src/cmd/admin/delete-user.ts","../src/cmd/admin/instance-stats.ts","../src/resource_id.ts","../src/cmd/maintenance/list-resources.ts","../src/cmd/maintenance/set-resource-error.ts","../src/cli.ts"],"sourcesContent":["import type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { createPlConnection, createAdminPlConnection } from \"./connection\";\nimport { getProjectListRid, navigateToUserRoot } from \"./project_ops\";\n\n/**\n * Low-level: get an authenticated PlClient without resolving a project list.\n * Use this for commands that navigate to multiple users (e.g. admin copy-project).\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connectClient(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n}): Promise<PlClient> {\n if (flags.adminUser && flags.adminPassword) {\n return createAdminPlConnection({\n address: flags.address,\n adminUser: flags.adminUser,\n adminPassword: flags.adminPassword,\n });\n }\n return createPlConnection({\n address: flags.address,\n user: flags.user,\n password: flags.password,\n });\n}\n\n/**\n * Connect and resolve the project list for a single user.\n * In admin mode (--admin-user + --admin-password + --target-user), operates on the target user's data.\n * In user mode, operates on the authenticated user's own data.\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connect(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n targetUser?: string;\n}): Promise<{ pl: PlClient; projectListRid: SignedResourceId }> {\n const hasAdminUser = !!flags.adminUser;\n const hasAdminPassword = !!flags.adminPassword;\n const hasTarget = !!flags.targetUser;\n\n // Validate flag combinations\n if (hasTarget && !(hasAdminUser && hasAdminPassword)) {\n throw new Error(\"--target-user requires --admin-user and --admin-password\");\n }\n if ((hasAdminUser || hasAdminPassword) && !hasTarget) {\n throw new Error(\"--admin-user/--admin-password require --target-user for project commands\");\n }\n\n const pl = await connectClient(flags);\n\n let projectListRid: SignedResourceId;\n if (hasTarget) {\n const nav = await navigateToUserRoot(pl, flags.targetUser!);\n projectListRid = nav.projectListRid;\n } else {\n projectListRid = await getProjectListRid(pl);\n }\n\n return { pl, projectListRid };\n}\n","import { Command, Option } from \"commander\";\nimport type { OutputFormat } from \"./output\";\n\n/** Add one or more groups of options to a command, preserving group order. */\nexport function addOptions(cmd: Command, ...optionGroups: Option[][]): Command {\n for (const group of optionGroups) {\n for (const opt of group) cmd.addOption(opt);\n }\n return cmd;\n}\n\n/** Server address only (for commands with a fixed output format). */\nexport const AddressOptions = (): Option[] => [\n new Option(\"-a, --address <url>\", \"Platforma server address\")\n .env(\"PL_ADDRESS\")\n .makeOptionMandatory(),\n];\n\nexport const GlobalOptions = (\n formatDefault: OutputFormat = \"text\",\n allowedFormats: OutputFormat[] = [\"text\", \"json\"],\n): Option[] => [\n ...AddressOptions(),\n new Option(\"-f, --format <format>\", \"Output format\")\n .choices(allowedFormats)\n .default(formatDefault),\n];\n\nexport const UserAuthOptions = (): Option[] => [\n new Option(\"-u, --user <user>\", \"Username for authentication\").env(\"PL_USER\"),\n new Option(\"-p, --password <password>\", \"Password for authentication\").env(\"PL_PASSWORD\"),\n];\n\n/** Admin credentials only (for purely admin commands like copy-project). */\nexport const AdminAuthOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username\")\n .env(\"PL_ADMIN_USER\")\n .makeOptionMandatory(),\n new Option(\"--admin-password <password>\", \"Admin/controller password\")\n .env(\"PL_ADMIN_PASSWORD\")\n .makeOptionMandatory(),\n];\n\n/** Admin credentials + target user (for regular commands that can optionally operate on another user). */\nexport const AdminTargetOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username (enables admin mode)\").env(\n \"PL_ADMIN_USER\",\n ),\n new Option(\"--admin-password <password>\", \"Admin/controller password\").env(\"PL_ADMIN_PASSWORD\"),\n new Option(\n \"--target-user <user>\",\n \"Operate on this user's data (requires admin credentials)\",\n ).env(\"PL_TARGET_USER\"),\n];\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { listProjects } from \"../../project_ops\";\nimport { formatTable, formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectListCommand(): Command {\n const cmd = new Command(\"list\").description(\"List all projects for the authenticated user.\");\n\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const projects = await listProjects(pl, projectListRid);\n\n if (flags.format === \"json\") {\n outputJson(\n projects.map((p) => ({\n id: p.id,\n rid: resourceIdToString(p.rid),\n label: p.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n } else {\n if (projects.length === 0) {\n outputText(\"No projects found.\");\n return;\n }\n\n outputText(\n formatTable(\n [\"ID\", \"RID\", \"LABEL\", \"CREATED\", \"LAST MODIFIED\"],\n projects.map((p) => [\n p.id,\n resourceIdToString(p.rid),\n p.label,\n formatDate(p.created),\n formatDate(p.lastModified),\n ]),\n ),\n );\n outputText(`\\n${projects.length} project(s)`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, getProjectInfo } from \"../../project_ops\";\nimport { formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectInfoCommand(): Command {\n const cmd = new Command(\"info\").description(\"Show detailed information about a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n const info = await getProjectInfo(pl, id, rid);\n\n if (flags.format === \"json\") {\n outputJson({\n id: info.id,\n rid: resourceIdToString(info.rid),\n label: info.label,\n schemaVersion: info.schemaVersion,\n blockCount: info.blockCount,\n blockIds: info.blockIds,\n created: info.created.toISOString(),\n lastModified: info.lastModified.toISOString(),\n });\n } else {\n outputText(`Project: ${info.label}`);\n outputText(`ID: ${info.id}`);\n outputText(`RID: ${resourceIdToString(info.rid)}`);\n outputText(`Schema: ${info.schemaVersion ?? \"(unknown)\"}`);\n outputText(`Blocks: ${info.blockCount}`);\n if (info.blockIds.length > 0) {\n for (const bid of info.blockIds) {\n outputText(` - ${bid}`);\n }\n }\n outputText(`Created: ${formatDate(info.created)}`);\n outputText(`Last Modified: ${formatDate(info.lastModified)}`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDuplicateCommand(): Command {\n const cmd = new Command(\"duplicate\").description(\n \"Duplicate a project within the same user. Auto-renames on collision by default.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"-n, --name <name>\", \"Name for the duplicate\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { rid: sourceRid } = await resolveProject(pl, projectListRid, project);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"duplicateProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, projectListRid);\n\n // Compute new label\n let newLabel: string;\n if (flags.name) {\n if (!flags.autoRename && existingLabels.includes(flags.name)) {\n throw new Error(`Project name \"${flags.name}\" already exists.`);\n }\n newLabel = existingLabels.includes(flags.name)\n ? deduplicateName(flags.name, existingLabels)\n : flags.name;\n } else {\n newLabel = deduplicateName(sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const projectResourceId = await newPrj.globalId;\n const projectId = resourceIdToString(projectResourceId);\n return { id: projectId, rid: projectResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({ id: result.id, rid: resourceIdToString(result.rid), label: result.label });\n } else {\n outputText(`Duplicated project as \"${result.label}\" (id: ${result.id})`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, renameProject } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectRenameCommand(): Command {\n const cmd = new Command(\"rename\").description(\"Rename a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.addOption(new Option(\"-n, --name <name>\", \"New name for the project\").makeOptionMandatory());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n\n await renameProject(pl, rid, flags.name);\n\n if (flags.format === \"json\") {\n outputJson({ id, rid: resourceIdToString(rid), label: flags.name });\n } else {\n outputText(`Renamed project to \"${flags.name}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, deleteProject, getProjectInfo } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDeleteCommand(): Command {\n const cmd = new Command(\"delete\").description(\n \"Delete a project. This permanently destroys all project data.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid, fieldName } = await resolveProject(pl, projectListRid, project);\n\n const info = await getProjectInfo(pl, id, rid);\n\n if (!flags.force) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\n `Delete project \"${info.label}\" (${info.blockCount} blocks)? [y/N] `,\n resolve,\n );\n });\n if (answer.toLowerCase() !== \"y\") {\n outputText(\"Aborted.\");\n return;\n }\n } finally {\n rl.close();\n }\n }\n\n await deleteProject(pl, projectListRid, fieldName);\n\n if (flags.format === \"json\") {\n outputJson({ deleted: true, id, label: info.label });\n } else {\n outputText(`Deleted project \"${info.label}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n navigateToUserRoot,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function adminCopyProjectCommand(): Command {\n const cmd = new Command(\"copy-project\").description(\n \"Copy a project from one user to another. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--source-user <user>\",\n \"Username of the source project owner\",\n ).makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--source-project <project>\", \"Source project ID or label\").makeOptionMandatory(),\n );\n cmd.option(\n \"--target-user <user>\",\n \"Username of the target user (defaults to source-user for same-user copy)\",\n );\n cmd.option(\"-n, --name <name>\", \"Name for the copied project\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const targetUser = flags.targetUser ?? flags.sourceUser;\n\n const source = await navigateToUserRoot(pl, flags.sourceUser);\n const { rid: sourceRid } = await resolveProject(\n pl,\n source.projectListRid,\n flags.sourceProject,\n );\n\n const target =\n targetUser === flags.sourceUser ? source : await navigateToUserRoot(pl, targetUser);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"adminCopyProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, target.projectListRid);\n\n let newLabel: string = flags.name ?? sourceLabel;\n\n if (existingLabels.includes(newLabel)) {\n if (!flags.autoRename) {\n throw new Error(`Project name \"${newLabel}\" already exists for target user.`);\n }\n newLabel = deduplicateName(flags.name ?? sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(target.projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const prjResourceId = await newPrj.globalId;\n const prjId = resourceIdToString(prjResourceId);\n return { id: prjId, rid: prjResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({\n id: result.id,\n rid: resourceIdToString(result.rid),\n label: result.label,\n sourceUser: flags.sourceUser,\n targetUser,\n });\n } else {\n outputText(\n `Copied project from ${flags.sourceUser} to ${targetUser} as \"${result.label}\" (id: ${result.id}, rid: ${resourceIdToString(result.rid)})`,\n );\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { isPermissionDenied } from \"@milaboratories/pl-client\";\nimport { Command } from \"commander\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson, outputText, outputCsv } from \"../../output\";\n\nexport default function adminUserListCommand(): Command {\n const cmd = new Command(\"user-list\").description(\n \"List all known users' logins from a live server. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"csv\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n let users;\n try {\n users = await pl.listUsers();\n } catch (err) {\n if (isPermissionDenied(err))\n throw new Error(\n \"The server does not let this user list users. \" +\n \"Check the server option '--show-user-list-to' and the role of the user.\",\n { cause: err },\n );\n throw err;\n }\n const logins = users.map((u) => u.login).sort();\n if (flags.format === \"json\") outputJson(logins);\n else if (flags.format === \"text\") outputText(logins.join(\"\\n\"));\n else\n outputCsv(\n [\"login\"],\n logins.map((l) => [l]),\n );\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n ensureUserProjectList,\n listProjectIdentities,\n moveProjects,\n openUserRoot,\n} from \"../../project_ops\";\nimport type { MovedProject, ProjectIdentityWithLabel } from \"../../project_ops\";\nimport { formatTable, outputJson, outputText } from \"../../output\";\n\nexport default function adminDeleteUserCommand(): Command {\n const cmd = new Command(\"delete-user\").description(\n \"Delete a user account. Optionally re-homes the user's projects to another user first. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\"<user>\", \"Username of the account to delete\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--move-projects-to <user>\",\n \"Re-home the deleted user's projects to this user before deleting the account\",\n ),\n );\n cmd.addOption(\n new Option(\n \"--delete-projects\",\n \"Delete the user's projects along with the account, losing their data\",\n ),\n );\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (user: string, flags) => {\n // The two modes are alternatives, not a combination: one keeps the projects, the other\n // destroys them, and a request for both says nothing about which was meant.\n if (flags.moveProjectsTo && flags.deleteProjects) {\n throw new Error(\"--move-projects-to and --delete-projects are mutually exclusive\");\n }\n if (flags.moveProjectsTo === user) {\n throw new Error(\"--move-projects-to must name a different user than the one being deleted\");\n }\n // Caught here as well as server-side, where it is authoritative: the operator gets the reason\n // instead of a failure from whichever lookup happens to run first.\n if (flags.adminUser === user) {\n throw new Error(\n `Refusing to delete \"${user}\" — it is the account these credentials authenticate as.`,\n );\n }\n\n const pl = await connectClient(flags);\n try {\n const source = await openUserRoot(pl, user);\n // No project list means the account never opened the app, so it owns nothing — a state to\n // delete straight through, not to fail on.\n const projects =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n\n // Neither mode given while the account still owns projects: refuse rather than pick. Both\n // defaults are wrong to assume — one silently destroys data, the other silently hands it to\n // someone. An account with no projects has nothing to decide about, so it just proceeds.\n if (projects.length > 0 && !flags.moveProjectsTo && !flags.deleteProjects) {\n throw new Error(\n `User \"${user}\" owns ${projects.length} project(s). Pass --move-projects-to <user> to ` +\n \"re-home them, or --delete-projects to delete them with the account.\",\n );\n }\n\n const confirmed = await confirmDeletion(user, projects, flags);\n if (!confirmed) {\n outputText(\"Aborted.\");\n return;\n }\n\n let moved: MovedProject[] = [];\n if (flags.moveProjectsTo && projects.length > 0) {\n const target = await openUserRoot(pl, flags.moveProjectsTo);\n // Created if the target has none, so re-homing to a user who has never opened the app\n // works rather than failing halfway with the account still present.\n const targetList = await ensureUserProjectList(pl, target.userRoot);\n moved = await moveProjects(pl, source.projectListRid!, targetList);\n }\n\n // deleteUser takes the root and everything still attached to it. The listing, the prompt and\n // the move each ran in an earlier transaction, so re-read: a project attached since then would\n // be destroyed without ever being reviewed.\n const remaining =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n assertProjectsAccountedFor(user, flags, projects, remaining);\n\n const report = await pl.deleteUser(user);\n\n if (flags.format === \"json\") {\n outputJson({\n deleted: true,\n user,\n movedTo: flags.moveProjectsTo ?? null,\n movedProjects: moved,\n deletedProjects: flags.moveProjectsTo ? [] : remaining.map((p) => p.label),\n userRootId: report.userRootId === undefined ? null : report.userRootId.toString(),\n userRootDeleted: report.userRootDeleted,\n revokedGrants: report.revokedGrants,\n removedIdentityIndexEntries: report.removedIdentityIndexEntries,\n });\n } else {\n outputText(renderResult(user, flags.moveProjectsTo, moved, remaining));\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/**\n * Refuses while the root holds a project the operator never agreed to lose — attached after the\n * listing, or left behind by the move.\n *\n * A last read, not a lock: it closes the prompt-sized window, not the round trip that follows.\n */\nfunction assertProjectsAccountedFor(\n user: string,\n flags: { moveProjectsTo?: string },\n approved: ProjectIdentityWithLabel[],\n remaining: ProjectIdentityWithLabel[],\n): void {\n if (flags.moveProjectsTo) {\n if (remaining.length === 0) return;\n throw new Error(\n `User \"${user}\" still owns ${remaining.length} project(s) after the move: ` +\n `${remaining.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"the projects were attached while the move ran. Re-run the command to move them too.\",\n );\n }\n\n const approvedIds = new Set(approved.map((p) => p.id));\n const unapproved = remaining.filter((p) => !approvedIds.has(p.id));\n if (unapproved.length === 0) return;\n throw new Error(\n `User \"${user}\" gained ${unapproved.length} project(s) since the list you confirmed: ` +\n `${unapproved.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"deleting it now would destroy them unreviewed. Re-run the command to see the current list.\",\n );\n}\n\n/** Asks the operator to confirm, naming the affected projects and their fate. */\nasync function confirmDeletion(\n user: string,\n projects: ProjectIdentityWithLabel[],\n flags: { moveProjectsTo?: string; force?: boolean },\n): Promise<boolean> {\n if (flags.force) return true;\n\n const fate = flags.moveProjectsTo\n ? `${projects.length} project(s) will move to \"${flags.moveProjectsTo}\"`\n : projects.length > 0\n ? `${projects.length} project(s) will be PERMANENTLY DELETED`\n : \"the account owns no projects\";\n\n process.stderr.write(`Delete user \"${user}\"? ${fate}.\\n`);\n if (projects.length > 0) {\n process.stderr.write(projects.map((p) => ` - ${p.label}`).join(\"\\n\") + \"\\n\");\n }\n\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", resolve);\n });\n return answer.toLowerCase() === \"y\";\n } finally {\n rl.close();\n }\n}\n\nfunction renderResult(\n user: string,\n movedTo: string | undefined,\n moved: MovedProject[],\n projects: ProjectIdentityWithLabel[],\n): string {\n const lines: string[] = [];\n\n if (movedTo) {\n if (moved.length > 0) {\n lines.push(`Moved ${moved.length} project(s) from ${user} to ${movedTo}:`);\n lines.push(\n formatTable(\n [\"id\", \"name\", \"name in target\"],\n moved.map((p) => [p.id, p.sourceLabel, p.targetLabel]),\n ),\n );\n } else {\n lines.push(`User ${user} had no projects to move.`);\n }\n } else if (projects.length > 0) {\n lines.push(`Deleted ${projects.length} project(s) belonging to ${user}:`);\n lines.push(projects.map((p) => ` - ${p.label}`).join(\"\\n\"));\n }\n\n lines.push(`Deleted user \"${user}\".`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { InstanceStatsContextTypeName, parseInstanceStats } from \"@milaboratories/pl-middle-layer\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson } from \"../../output\";\n\nexport default function adminInstanceStatsCommand(): Command {\n const cmd = new Command(\"instance-stats\").description(\"Show the instance statistics as JSON.\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const [context] = await pl.listSharedResourcesByType(InstanceStatsContextTypeName);\n if (context === undefined) throw new Error(\"The instance has no instance statistics.\");\n const kvs = await pl.withReadTx(\"instanceStats\", (tx) => tx.listKeyValuesString(context));\n outputJson(parseInstanceStats(kvs));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import {\n asSignedResourceId,\n createSignedResourceId,\n isLocalResourceId,\n resourceIdFromString,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\n\n/**\n * Admin and controller roles do not need resource signatures: an ID without a signature\n * is accepted by the backend for these roles.\n */\nexport function parseResourceId(raw: string): SignedResourceId {\n const str = raw.trim();\n if (str.includes(\"|\")) return asSignedResourceId(str);\n\n let id: bigint | undefined = resourceIdFromString(str);\n if (id === undefined && /^\\d+$/.test(str)) id = BigInt(str);\n if (id === undefined || id === 0n || isLocalResourceId(id))\n throw new Error(`not a global resource ID: ${raw}`);\n\n return createSignedResourceId(id);\n}\n","import { once } from \"node:events\";\nimport { Command, InvalidArgumentError, Option } from \"commander\";\nimport {\n isNotNullSignedResourceId,\n resourceIdToString,\n resourceType,\n resourceTypeToString,\n type FieldData,\n type KeyValue,\n type OptionalSignedResourceId,\n type ResourceData,\n type ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { parseResourceId } from \"../../resource_id\";\n\nexport default function maintenanceListResourcesCommand(): Command {\n const cmd = new Command(\"list-resources\").description(\n \"List resources of one type as JSON lines, in ascending order of resource ID. \" +\n \"Resource data and key-value values are printed as JSON when they are valid JSON, \" +\n 'as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. ' +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"--type <name:version>\", \"Resource type to list (e.g. 'Blob/work:1')\")\n .argParser(parseResourceTypeArg)\n .makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--limit <n>\", \"Maximum number of resources to list. 0 lists all resources\")\n .argParser(parseNonNegativeInt)\n .default(0),\n );\n cmd.addOption(\n new Option(\n \"--after <resource-id>\",\n \"List only resources with IDs greater than this ID. \" +\n \"To get the next page, give the ID of the last resource of the previous page\",\n ).argParser(parseResourceId),\n );\n cmd.option(\n \"--load-fields\",\n \"Load the fields and the error of each resource ('fields' and 'error' keys)\",\n false,\n );\n cmd.option(\"--load-kv\", \"Load the key-value entries of each resource ('kv' key)\", false);\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const resources = await pl.withReadTx(\"listResources\", async (tx) => {\n const list = await tx.listResourcesByType(flags.type, {\n limit: flags.limit,\n after: flags.after,\n loadFields: flags.loadFields,\n });\n return await Promise.all(\n list.map(async (resource) => ({\n resource,\n kv: flags.loadKv ? await tx.listKeyValues(resource.id) : undefined,\n })),\n );\n });\n\n for (const { resource, kv } of resources) {\n const line = JSON.stringify(toJson(resource, flags.loadFields, kv)) + \"\\n\";\n // Wait for a slow reader: else the output collects in memory a second time.\n if (!process.stdout.write(line)) await once(process.stdout, \"drain\");\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\nfunction toJson(\n r: ResourceData,\n withFields: boolean,\n kv: KeyValue[] | undefined,\n): Record<string, unknown> {\n return {\n id: resourceIdToString(r.id),\n type: resourceTypeToString(r.type),\n kind: r.kind,\n originalId: optionalIdToString(r.originalResourceId),\n inputsLocked: r.inputsLocked,\n outputsLocked: r.outputsLocked,\n ready: r.resourceReady,\n final: r.final,\n data: r.data === undefined || r.data.length === 0 ? null : decodeBytes(r.data),\n // The backend sends the resource error as a field: without fields it is not known.\n ...(withFields\n ? { error: optionalIdToString(r.error), fields: r.fields.map(fieldToJson) }\n : {}),\n ...(kv === undefined\n ? {}\n : { kv: Object.fromEntries(kv.map((e) => [e.key, decodeBytes(e.value)])) }),\n };\n}\n\nfunction fieldToJson(f: FieldData): Record<string, unknown> {\n return {\n name: f.name,\n type: f.type,\n status: f.status,\n value: optionalIdToString(f.value),\n error: optionalIdToString(f.error),\n valueIsFinal: f.valueIsFinal,\n };\n}\n\nfunction optionalIdToString(id: OptionalSignedResourceId): string | null {\n return isNotNullSignedResourceId(id) ? resourceIdToString(id) : null;\n}\n\n/** JSON value when the bytes are valid JSON, text when valid UTF-8, {\"base64\": ...} otherwise. */\nfunction decodeBytes(bytes: Uint8Array): unknown {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return { base64: Buffer.from(bytes).toString(\"base64\") };\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseResourceTypeArg(value: string): ResourceType {\n const sep = value.lastIndexOf(\":\");\n if (sep <= 0 || sep === value.length - 1)\n throw new InvalidArgumentError(`expected <name>:<version>, e.g. 'Blob/work:1': ${value}`);\n return resourceType(value.slice(0, sep), value.slice(sep + 1));\n}\n\nfunction parseNonNegativeInt(value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0)\n throw new InvalidArgumentError(`not a non-negative integer: ${value}`);\n return n;\n}\n","import { Command, Option } from \"commander\";\nimport { isNotNullSignedResourceId, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputText } from \"../../output\";\nimport { parseResourceId } from \"../../resource_id\";\n\nconst DefaultErrorMessage =\n \"Manual error set by administrator to trigger blocks re-run. \" +\n \"Run block once again to get rid of it.\";\n\nexport default function maintenanceSetResourceErrorCommand(): Command {\n const cmd = new Command(\"set-resource-error\").description(\n \"Put an error on one or more resources in a single transaction. \" +\n \"Resources that already have an error are skipped. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\n \"<resource-id...>\",\n \"Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, \" +\n \"or as signed IDs (<decimal ID>|<signature hex>)\",\n );\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"-m, --error-message <message>\", \"Error message to put on the resources\").default(\n DefaultErrorMessage,\n ),\n );\n cmd.option(\n \"--skip-missing\",\n \"Skip resources that do not exist instead of failing the whole transaction\",\n false,\n );\n\n cmd.action(async (rawIds: string[], flags) => {\n // Parse all IDs before the connection, so that a typo does not leave a half-done job.\n const ids = rawIds.map(parseResourceId);\n\n const pl = await connectClient(flags);\n try {\n const result = await pl.withWriteTx(\"setResourceError\", async (tx) => {\n const found = await Promise.all(\n ids.map(async (id) => ({\n id,\n data: flags.skipMissing\n ? await tx.getResourceDataIfExists(id, true)\n : await tx.getResourceData(id, true, true),\n })),\n );\n\n const missing = found.filter((r) => r.data === undefined).map((r) => r.id);\n const resources = found.flatMap((r) => (r.data === undefined ? [] : [r.data]));\n const targets = resources.filter((r) => !isNotNullSignedResourceId(r.error));\n const skipped = resources.filter((r) => isNotNullSignedResourceId(r.error));\n\n if (targets.length > 0) {\n // One error resource for all targets: the backend links it to each target separately.\n const error = tx.createError(flags.errorMessage);\n for (const r of targets) tx.setResourceError(r.id, error);\n await tx.commit();\n }\n\n return { targets, skipped, missing };\n });\n\n for (const id of result.missing)\n outputText(`skipped ${resourceIdToString(id)}: resource does not exist`);\n for (const r of result.skipped)\n outputText(`skipped ${resourceIdToString(r.id)}: resource already has an error`);\n for (const r of result.targets) outputText(`error set ${resourceIdToString(r.id)}`);\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport projectListCommand from \"./cmd/project/list\";\nimport projectInfoCommand from \"./cmd/project/info\";\nimport projectDuplicateCommand from \"./cmd/project/duplicate\";\nimport projectRenameCommand from \"./cmd/project/rename\";\nimport projectDeleteCommand from \"./cmd/project/delete\";\nimport adminCopyProjectCommand from \"./cmd/admin/copy-project\";\nimport adminUserListCommand from \"./cmd/admin/user-list\";\nimport adminDeleteUserCommand from \"./cmd/admin/delete-user\";\nimport adminInstanceStatsCommand from \"./cmd/admin/instance-stats\";\nimport maintenanceListResourcesCommand from \"./cmd/maintenance/list-resources\";\nimport maintenanceSetResourceErrorCommand from \"./cmd/maintenance/set-resource-error\";\n\nexport function buildProgram(): Command {\n const program = new Command();\n program.name(\"pl-cli\").description(\"Platforma command-line client\");\n\n const project = new Command(\"project\").description(\"Manage projects\");\n project.addCommand(projectListCommand());\n project.addCommand(projectInfoCommand());\n project.addCommand(projectDuplicateCommand());\n project.addCommand(projectRenameCommand());\n project.addCommand(projectDeleteCommand());\n program.addCommand(project);\n\n const admin = new Command(\"admin\").description(\n \"Admin operations (requires controller credentials)\",\n );\n admin.addCommand(adminCopyProjectCommand());\n admin.addCommand(adminUserListCommand());\n admin.addCommand(adminDeleteUserCommand());\n admin.addCommand(adminInstanceStatsCommand());\n program.addCommand(admin);\n\n const maintenance = new Command(\"maintenance\").description(\n \"Low-level server state repair (requires admin/controller credentials)\",\n );\n maintenance.addCommand(maintenanceListResourcesCommand());\n maintenance.addCommand(maintenanceSetResourceErrorCommand());\n program.addCommand(maintenance);\n\n return program;\n}\n\nexport async function run(argv: string[] = process.argv): Promise<void> {\n await buildProgram().parseAsync(argv);\n}\n"],"mappings":";;;;;;;;AAUA,eAAsBkB,EAAc,GAMd;CAQpB,OAPIC,EAAM,aAAaA,EAAM,gBACpBjB,EAAwB;EAC7B,SAASiB,EAAM;EACf,WAAWA,EAAM;EACjB,eAAeA,EAAM;CACvB,CAAC,IAEIH,EAAmB;E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AAQ,CAAC,CAAC,YAAY,+BAA+B;CAElE,IAAMK,IAAU,IAAIL,EAAQ,SAAS,CAAC,CAAC,YAAY,iBAAiB;CAMpE,AALAK,EAAQ,WAAWN,EAAmB,CAAC,GACvCM,EAAQ,WAAWD,EAAmB,CAAC,GACvCC,EAAQ,WAAWK,EAAwB,CAAC,GAC5CL,EAAQ,WAAWmB,EAAqB,CAAC,GACzCnB,EAAQ,WAAWqB,EAAqB,CAAC,GACzCiF,EAAQ,WAAWtG,CAAO;CAE1B,IAAMuG,IAAQ,IAAI5G,EAAQ,OAAO,CAAC,CAAC,YACjC,oDACF;CAKA,AAJA4G,EAAM,WAAW7E,EAAwB,CAAC,GAC1C6E,EAAM,WAAWxE,EAAqB,CAAC,GACvCwE,EAAM,WAAWjE,GAAuB,CAAC,GACzCiE,EAAM,WAAWhD,GAA0B,CAAC,GAC5C+C,EAAQ,WAAWC,CAAK;CAExB,IAAMC,IAAc,IAAI7G,EAAQ,aAAa,CAAC,CAAC,YAC7C,uEACF;CAKA,OAJA6G,EAAY,WAAWrC,GAAgC,CAAC,GACxDqC,EAAY,WAAWX,GAAmC,CAAC,GAC3DS,EAAQ,WAAWE,CAAW,GAEvBF;AACT;AAEA,eAAsBG,GAAI,IAAiB,QAAQ,MAAqB;CACtE,MAAMJ,EAAa,CAAC,CAAC,WAAWK,CAAI;AACtC"}
1
+ {"version":3,"file":"cli.js","names":["usedSession","authenticatedLogin","requireInstanceId","probeInstance","redactAddress","resetUsedSession","parsePlToken","SessionRequiredError","createPlConnection","outputCsv","getExistingLabelsInTx","MinSessionBackendVersion","listProjectIdentities","navigateToUserRoot","openUserRoot","formatTable","formatDate","ensureUserProjectList","SessionStore","sessionRefusedMessage","listProjects","resolveProject","deleteProject","getProjectInfo","renameProject","duplicateProject","getProjectListRid","deduplicateName","moveProjects","outputJson","createAdminPlConnection","OldBackendMessage","outputText","addOptions","optionGroups","group","opt","cmd","AddressOptions","option","opts","Option","GlobalOptions","allowedFormats","formatDefault","UserAuthOptions","AdminAuthOptions","AdminTargetOptions","promptLine","input","output","question","rl","createInterface","resolve","value","onData","ch","chunk","reject","runOidcLogin","args","method","pkce","generatePkcePair","state","randomBytes","listener","listenForCallback","redirectUri","discoverEndpoints","authUrl","authorizationEndpoint","nonce","exchangeAuthCode","requireSecureUrl","url","raw","what","sanitizeForTerminal","isLoopbackHost","hostname","text","openInBrowser","command","cmdArgs","child","spawn","codeVerifier","createHash","callbackPage","message","signal","abortError","closed","close","server","createServer","request","response","params","expectedState","error","code","port","bindToFirstAvailablePort","ports","err","promise","portIndex","onListening","cleanup","onError","tryNextPort","issuer","doc","body","loginCommand","Command","n","v","flags","listMethods","login","formatLoginMethods","methods","m","unauth","UnauthenticatedPlClient","plAddressToConfig","config","address","probedId","instanceId","pickMethod","kind","credentials","token","ssoLogin","passwordLogin","claims","now","expiry","store","found","isToken","user","password","attempt","tokenResponse","redirect","instanceIdOf","resolveInstance","logoutCommand","logout","where","def","removed","which","sessionListCommand","sessionList","rows","isDefault","expiresAt","session","r","InstanceOptions","sessionSelectCommand","sessionSelect","sessionRemoveCommand","sessionRemove","connectClient","connect","hasAdminUser","hasAdminPassword","hasTarget","pl","projectListRid","projectListCommand","projects","p","resourceIdToString","projectInfoCommand","project","info","id","rid","bid","projectDuplicateCommand","sourceRid","newId","randomUUID","result","sourceMetaStr","tx","ProjectMetaKey","sourceLabel","existingLabels","newLabel","newPrj","field","projectResourceId","projectRenameCommand","projectDeleteCommand","fieldName","adminCopyProjectCommand","targetUser","source","target","prjResourceId","adminUserListCommand","users","isPermissionDenied","logins","u","l","adminDeleteUserCommand","confirmDeletion","moved","targetList","remaining","report","renderResult","assertProjectsAccountedFor","approvedIds","approved","unapproved","fate","lines","movedTo","adminInstanceStatsCommand","context","InstanceStatsContextTypeName","kvs","parseInstanceStats","parseResourceId","str","asSignedResourceId","resourceIdFromString","isLocalResourceId","createSignedResourceId","maintenanceListResourcesCommand","parseResourceTypeArg","parseNonNegativeInt","resources","list","resource","line","toJson","kv","once","resourceTypeToString","optionalIdToString","decodeBytes","withFields","fieldToJson","f","isNotNullSignedResourceId","bytes","sep","InvalidArgumentError","resourceType","DefaultErrorMessage","maintenanceSetResourceErrorCommand","ids","rawIds","missing","targets","skipped","buildProgram","program","noteCredentialsFromEnv","actionCommand","admin","maintenance","credentialEnv","fromEnv","env","run","argv","isUnauthenticated"],"sources":["../src/cmd-opts.ts","../src/prompt.ts","../src/sso.ts","../src/cmd/login.ts","../src/instance.ts","../src/cmd/logout.ts","../src/cmd/session/list.ts","../src/cmd/session/select.ts","../src/cmd/session/remove.ts","../src/base_command.ts","../src/cmd/project/list.ts","../src/cmd/project/info.ts","../src/cmd/project/duplicate.ts","../src/cmd/project/rename.ts","../src/cmd/project/delete.ts","../src/cmd/admin/copy-project.ts","../src/cmd/admin/user-list.ts","../src/cmd/admin/delete-user.ts","../src/cmd/admin/instance-stats.ts","../src/resource_id.ts","../src/cmd/maintenance/list-resources.ts","../src/cmd/maintenance/set-resource-error.ts","../src/cli.ts"],"sourcesContent":["import { Command, Option } from \"commander\";\nimport type { OutputFormat } from \"./output\";\n\n/** Add one or more groups of options to a command, preserving group order. */\nexport function addOptions(cmd: Command, ...optionGroups: Option[][]): Command {\n for (const group of optionGroups) {\n for (const opt of group) cmd.addOption(opt);\n }\n return cmd;\n}\n\n/** Server address. Optional by default: without it, commands use the address of the default\n * stored session (see `pl-cli session select`). */\nexport const AddressOptions = (opts: { required?: boolean } = {}): Option[] => {\n const option = opts.required\n ? new Option(\"-a, --address <url>\", \"Platforma server address\").env(\"PL_ADDRESS\")\n : new Option(\n \"-a, --address <url>\",\n \"Platforma server address. Default: the address of the default stored session\",\n ).env(\"PL_ADDRESS\");\n return [opts.required ? option.makeOptionMandatory() : option];\n};\n\nexport const GlobalOptions = (\n formatDefault: OutputFormat = \"text\",\n allowedFormats: OutputFormat[] = [\"text\", \"json\"],\n): Option[] => [\n ...AddressOptions(),\n new Option(\"-f, --format <format>\", \"Output format\")\n .choices(allowedFormats)\n .default(formatDefault),\n];\n\nexport const UserAuthOptions = (): Option[] => [\n new Option(\n \"-u, --user <user>\",\n \"Username for authentication. Without --password, selects the stored session of this login\",\n ).env(\"PL_USER\"),\n new Option(\"-p, --password <password>\", \"Password for authentication\").env(\"PL_PASSWORD\"),\n];\n\n/** Admin credentials only (for purely admin commands like copy-project).\n * Without them, the command uses the stored session (see `pl-cli login`); the Backend checks\n * that its user has the admin role. */\nexport const AdminAuthOptions = (): Option[] => [\n new Option(\n \"--admin-user <user>\",\n \"Admin/controller username. Without --admin-password, selects the stored session of this login\",\n ).env(\"PL_ADMIN_USER\"),\n new Option(\"--admin-password <password>\", \"Admin/controller password\").env(\"PL_ADMIN_PASSWORD\"),\n];\n\n/** Admin credentials + target user (for regular commands that can optionally operate on another user). */\nexport const AdminTargetOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username (enables admin mode)\").env(\n \"PL_ADMIN_USER\",\n ),\n new Option(\"--admin-password <password>\", \"Admin/controller password\").env(\"PL_ADMIN_PASSWORD\"),\n new Option(\n \"--target-user <user>\",\n \"Operate on this user's data (requires admin credentials or an admin's stored session)\",\n ).env(\"PL_TARGET_USER\"),\n];\n","import { createInterface } from \"node:readline\";\n\n/** Reads one line from the terminal. Shows the typed characters unless `hidden` is true.\n * Fails when stdin is not a terminal, so scripts get an error instead of a wait. */\nexport async function promptLine(\n question: string,\n opts: { hidden?: boolean } = {},\n): Promise<string> {\n const input = process.stdin;\n const output = process.stderr;\n if (!input.isTTY)\n throw new Error(`Cannot ask for input: stdin is not a terminal. (${question.trim()})`);\n\n if (!opts.hidden) {\n const rl = createInterface({ input, output, terminal: true });\n try {\n return await new Promise<string>((resolve) => rl.question(question, resolve));\n } finally {\n rl.close();\n }\n }\n\n output.write(question);\n input.setRawMode(true);\n input.resume();\n input.setEncoding(\"utf8\");\n try {\n return await new Promise<string>((resolve, reject) => {\n let value = \"\";\n const onData = (chunk: string) => {\n for (const ch of chunk) {\n if (ch === \"\\r\" || ch === \"\\n\" || ch === \"\\u0004\") {\n input.removeListener(\"data\", onData);\n output.write(\"\\n\");\n resolve(value);\n return;\n }\n if (ch === \"\\u0003\") {\n input.removeListener(\"data\", onData);\n output.write(\"\\n\");\n reject(new Error(\"Cancelled.\"));\n return;\n }\n if (ch === \"\\u007f\" || ch === \"\\b\") value = value.slice(0, -1);\n else value += ch;\n }\n };\n input.on(\"data\", onData);\n });\n } finally {\n input.setRawMode(false);\n input.pause();\n }\n}\n","// Ported from the Desktop App (packages/main/src/sso.ts). Keep the two flows the same.\nimport { spawn } from \"node:child_process\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { createServer, type Server } from \"node:http\";\nimport type { SSOAuthMethod } from \"@milaboratories/pl-client\";\n\nexport interface RunOidcLoginArgs {\n method: SSOAuthMethod;\n /** One-time nonce from the Backend's BeginSSOLogin. */\n nonce: string;\n /** Client secret from the Backend's BeginSSOLogin. Sent to the identity provider token\n * endpoint when set (confidential clients, for example Google); absent for public clients. */\n clientSecret?: string;\n /** Called with the identity provider URL that the user must open. */\n openUrl: (url: string) => void | Promise<void>;\n /** Stops the flow: closes the loopback listener and cancels the token request. */\n signal?: AbortSignal;\n}\n\n/**\n * Runs the authorization code flow with PKCE (RFC 7636, S256) for a public client, as the\n * Desktop App does: listens on 127.0.0.1 on the first free redirect port that the Backend\n * advertises, sends the user to the identity provider, receives the code and exchanges it for\n * tokens. Returns the raw token response body. The caller gives this body to the Backend\n * (Login with SSO credentials) and must not keep it: only the Backend reads these tokens.\n */\nexport async function runOidcLogin(args: RunOidcLoginArgs): Promise<Uint8Array> {\n const { method, nonce } = args;\n // Check before the listener starts, so that a refused issuer leaves nothing open.\n requireSecureUrl(method.issuer, \"SSO issuer\");\n\n const pkce = generatePkcePair();\n const state = randomBytes(32).toString(\"base64url\");\n\n // Bind the listener first: the redirect URI must contain the port that is really bound.\n const listener = await listenForCallback(method.redirectPorts, state, args.signal);\n try {\n const redirectUri = `http://127.0.0.1:${listener.port}/callback`;\n\n const { authorizationEndpoint, tokenEndpoint } = await discoverEndpoints(\n method.issuer,\n args.signal,\n );\n\n const authUrl = new URL(authorizationEndpoint);\n authUrl.searchParams.set(\"response_type\", \"code\");\n authUrl.searchParams.set(\"client_id\", method.clientId);\n authUrl.searchParams.set(\"redirect_uri\", redirectUri);\n authUrl.searchParams.set(\"scope\", method.scopes);\n authUrl.searchParams.set(\"state\", state);\n authUrl.searchParams.set(\"nonce\", nonce);\n authUrl.searchParams.set(\"code_challenge\", pkce.codeChallenge);\n authUrl.searchParams.set(\"code_challenge_method\", pkce.codeChallengeMethod);\n if (method.resource) authUrl.searchParams.set(\"resource\", method.resource);\n if (method.prompt) authUrl.searchParams.set(\"prompt\", method.prompt);\n // Google issues a refresh token only with access_type=offline. The Backend keeps that refresh\n // token and uses it to renew the Platforma session; pl-cli never sees it.\n if (method.accessType) authUrl.searchParams.set(\"access_type\", method.accessType);\n\n await args.openUrl(authUrl.toString());\n const code = await listener.code;\n\n return await exchangeAuthCode({\n tokenEndpoint,\n code,\n redirectUri,\n clientId: method.clientId,\n codeVerifier: pkce.codeVerifier,\n clientSecret: args.clientSecret,\n resource: method.resource || undefined,\n signal: args.signal,\n });\n } finally {\n // Also on a failure before the callback (discovery, openUrl): an open listener keeps the\n // process alive until the timeout.\n listener.close();\n }\n}\n\n/** Accepts only `https:` URLs, and `http:` URLs to a loopback host (local test identity\n * providers). Other schemes (`file:`, application schemes) must not reach the browser launcher,\n * and plain HTTP to a remote host would send the code and the PKCE verifier in clear text. */\nexport function requireSecureUrl(raw: string, what: string): URL {\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new Error(`${what} is not a valid URL: ${sanitizeForTerminal(raw)}`);\n }\n if (url.protocol === \"https:\") return url;\n if (url.protocol === \"http:\" && isLoopbackHost(url.hostname)) return url;\n throw new Error(\n `${what} must use https (http is accepted only for localhost): ${sanitizeForTerminal(raw)}`,\n );\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n return (\n hostname === \"localhost\" ||\n hostname === \"[::1]\" ||\n hostname === \"::1\" ||\n /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(hostname)\n );\n}\n\n/** Removes control characters (terminal escape sequences included) from text that comes from\n * the identity provider, before pl-cli prints it. Keeps line feeds and tabs. */\nexport function sanitizeForTerminal(text: string): string {\n // oxlint-disable-next-line no-control-regex\n return text.replace(/[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f]/g, \"\");\n}\n\n/** Opens the URL in the default browser. Returns false if no browser command could start. */\nexport async function openInBrowser(url: string): Promise<boolean> {\n // The launchers start any registered handler, so allow web URLs only.\n requireSecureUrl(url, \"Sign-in URL\");\n const [command, cmdArgs] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? // rundll32 takes the URL as one argument; \"cmd /c start\" would split it at \"&\".\n [\"rundll32\", [\"url.dll,FileProtocolHandler\", url]]\n : [\"xdg-open\", [url]];\n return await new Promise<boolean>((resolve) => {\n try {\n const child = spawn(command, cmdArgs, { stdio: \"ignore\", detached: true });\n child.once(\"error\", () => resolve(false));\n child.once(\"spawn\", () => {\n child.unref();\n resolve(true);\n });\n } catch {\n resolve(false);\n }\n });\n}\n\ninterface PkcePair {\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: \"S256\";\n}\n\nfunction generatePkcePair(): PkcePair {\n const codeVerifier = randomBytes(64).toString(\"base64url\");\n const codeChallenge = createHash(\"sha256\").update(codeVerifier).digest().toString(\"base64url\");\n return { codeVerifier, codeChallenge, codeChallengeMethod: \"S256\" };\n}\n\nfunction callbackPage(message: string): string {\n return (\n \"<!doctype html><meta charset=utf-8><title>Platforma</title>\" +\n `<p>${message}</p><script>window.close()</script>`\n );\n}\n\ninterface CallbackListener {\n port: number;\n /** The authorization code. Rejects on an identity provider error or on abort. */\n code: Promise<string>;\n /** Stops the listener. Safe to call more than once. */\n close: () => void;\n}\n\n/** Binds a loopback HTTP server to the first free port of `ports`. Waits for a callback with the\n * expected state: a callback without it gets status 400 and the server keeps listening, so that\n * another web page cannot stop the sign-in. */\nasync function listenForCallback(\n ports: number[],\n expectedState: string,\n signal: AbortSignal | undefined,\n): Promise<CallbackListener> {\n if (signal?.aborted) throw abortError();\n\n const { promise, resolve, reject } = Promise.withResolvers<string>();\n // The caller may not await the code promise yet (for example, while discovery runs).\n promise.catch(() => {});\n\n let closed = false;\n const close = () => {\n if (closed) return;\n closed = true;\n server.close();\n server.closeAllConnections();\n reject(abortError());\n };\n\n const server = createServer((request, response) => {\n const url = new URL(request.url ?? \"/\", \"http://127.0.0.1\");\n if (url.pathname !== \"/callback\") {\n response.statusCode = 404;\n response.end();\n return;\n }\n response.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n const params = url.searchParams;\n if (params.get(\"state\") !== expectedState) {\n response.statusCode = 400;\n response.end(callbackPage(\"This sign-in request is not valid. Go back to the terminal.\"));\n return;\n }\n\n const error = params.get(\"error\");\n const code = params.get(\"code\");\n if (error) {\n response.end(callbackPage(\"Sign-in failed. Go back to the terminal for the details.\"));\n reject(\n new Error(\n sanitizeForTerminal(\n `Identity provider error: ${error}: ${params.get(\"error_description\") ?? \"\"}`,\n ),\n ),\n );\n } else if (!code) {\n response.end(callbackPage(\"Sign-in failed. Go back to the terminal for the details.\"));\n reject(new Error(\"The SSO callback has no code.\"));\n } else {\n response.end(callbackPage(\"Sign-in is complete. You can close this tab.\"));\n resolve(code);\n }\n close();\n });\n\n signal?.addEventListener(\"abort\", close, { once: true });\n\n const port = await bindToFirstAvailablePort(server, ports);\n server.on(\"error\", (err) => reject(new Error(`SSO loopback server error: ${err.message}`)));\n return { port, code: promise, close };\n}\n\nfunction bindToFirstAvailablePort(server: Server, ports: number[]): Promise<number> {\n const { promise, resolve, reject } = Promise.withResolvers<number>();\n if (ports.length === 0) {\n reject(new Error(\"The Backend advertises no SSO redirect ports.\"));\n return promise;\n }\n\n let portIndex = -1;\n const onListening = () => {\n cleanup();\n resolve(ports[portIndex]);\n };\n const onError = (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\") {\n tryNextPort();\n } else {\n cleanup();\n reject(new Error(`SSO loopback cannot bind port ${ports[portIndex]}: ${err.message}`));\n }\n };\n const cleanup = () => {\n server.removeListener(\"error\", onError);\n server.removeListener(\"listening\", onListening);\n };\n const tryNextPort = () => {\n portIndex += 1;\n if (portIndex >= ports.length) {\n cleanup();\n reject(new Error(`All SSO redirect ports are in use: ${ports.join(\", \")}`));\n return;\n }\n server.listen(ports[portIndex], \"127.0.0.1\");\n };\n\n server.on(\"listening\", onListening);\n server.on(\"error\", onError);\n tryNextPort();\n return promise;\n}\n\nfunction abortError(): Error {\n const error = new Error(\"SSO sign-in was cancelled.\");\n error.name = \"AbortError\";\n return error;\n}\n\n/** Reads the authorization and token endpoints from the OpenID Connect discovery document. */\nasync function discoverEndpoints(\n issuer: string,\n signal: AbortSignal | undefined,\n): Promise<{ authorizationEndpoint: string; tokenEndpoint: string }> {\n const url = `${issuer.replace(/\\/+$/, \"\")}/.well-known/openid-configuration`;\n const response = await fetch(url, { signal });\n if (!response.ok) throw new Error(`OIDC discovery ${url} failed: ${response.status}`);\n const doc: unknown = await response.json();\n if (\n typeof doc !== \"object\" ||\n doc === null ||\n !(\"authorization_endpoint\" in doc) ||\n !(\"token_endpoint\" in doc) ||\n typeof doc.authorization_endpoint !== \"string\" ||\n typeof doc.token_endpoint !== \"string\"\n )\n throw new Error(`OIDC discovery ${url} has no authorization_endpoint or token_endpoint.`);\n requireSecureUrl(doc.authorization_endpoint, \"SSO authorization endpoint\");\n requireSecureUrl(doc.token_endpoint, \"SSO token endpoint\");\n return {\n authorizationEndpoint: doc.authorization_endpoint,\n tokenEndpoint: doc.token_endpoint,\n };\n}\n\nasync function exchangeAuthCode(args: {\n tokenEndpoint: string;\n code: string;\n redirectUri: string;\n clientId: string;\n codeVerifier: string;\n clientSecret?: string;\n resource?: string;\n signal?: AbortSignal;\n}): Promise<Uint8Array> {\n const body: Record<string, string> = {\n grant_type: \"authorization_code\",\n code: args.code,\n redirect_uri: args.redirectUri,\n client_id: args.clientId,\n code_verifier: args.codeVerifier,\n };\n if (args.resource) body.resource = args.resource;\n if (args.clientSecret) body.client_secret = args.clientSecret;\n\n const response = await fetch(args.tokenEndpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(body).toString(),\n signal: args.signal,\n });\n const raw = new Uint8Array(await response.arrayBuffer());\n if (!response.ok)\n throw new Error(\n `Identity provider token endpoint returned ${response.status}: ` +\n sanitizeForTerminal(Buffer.from(raw).toString(\"utf8\")),\n );\n return raw;\n}\n","import { Command, Option } from \"commander\";\nimport {\n UnauthenticatedPlClient,\n plAddressToConfig,\n type AuthInformation,\n type LoginMethod,\n} from \"@milaboratories/pl-client\";\nimport { addOptions, AddressOptions } from \"../cmd-opts\";\nimport { redactAddress } from \"../address\";\nimport {\n OldBackendMessage,\n MinSessionBackendVersion,\n probeInstance,\n requireInstanceId,\n} from \"../connection\";\nimport { parsePlToken } from \"../jwt\";\nimport { formatTable, outputJson, outputText } from \"../output\";\nimport { promptLine } from \"../prompt\";\nimport { SessionStore, type SessionLoginKind } from \"../session_store\";\nimport { openInBrowser, runOidcLogin, sanitizeForTerminal } from \"../sso\";\n\nexport default function loginCommand(): Command {\n const cmd = new Command(\"login\").description(\n \"Sign in to a Backend and store the session. Later commands to the same Backend instance use \" +\n \"the stored session. Select the login method with --method <id>; see the IDs with \" +\n `--list-methods. Needs Backend v${MinSessionBackendVersion} or newer.`,\n );\n\n addOptions(cmd, AddressOptions({ required: true }));\n cmd.addOption(\n new Option(\n \"--method <id>\",\n \"ID of the login method (SSO provider, password or token method). Required to sign in\",\n ),\n );\n cmd.addOption(\n new Option(\"--list-methods\", \"Show the login methods of the Backend and exit; do not sign in\"),\n );\n cmd.addOption(\n new Option(\"-f, --format <format>\", \"Output format of --list-methods\")\n .choices([\"text\", \"json\"])\n .default(\"text\"),\n );\n cmd.addOption(\n new Option(\"-u, --user <user>\", \"Login for a password method. Asked for when not given\").env(\n \"PL_USER\",\n ),\n );\n cmd.addOption(\n new Option(\n \"-p, --password <password>\",\n \"Password, or the token for a token method. Asked for when not given\",\n ).env(\"PL_PASSWORD\"),\n );\n cmd.addOption(\n new Option(\"--no-browser\", \"Do not open a browser for SSO; only print the sign-in URL\"),\n );\n cmd.addOption(\n new Option(\"--timeout <seconds>\", \"How long to wait for the SSO sign-in to complete\")\n .default(300)\n .argParser((v) => {\n const n = Number(v);\n if (!Number.isFinite(n) || n <= 0) throw new Error(\"--timeout must be a positive number\");\n return n;\n }),\n );\n\n cmd.action(async (flags) => {\n if (flags.listMethods) await listMethods(flags);\n else await login(flags);\n });\n\n return cmd;\n}\n\nexport interface LoginFlags {\n address: string;\n user?: string;\n password?: string;\n method?: string;\n browser?: boolean;\n timeout?: number;\n}\n\n/** Formats login methods as a table: ID, KIND, TITLE, ISSUER (SSO only). */\nexport function formatLoginMethods(methods: LoginMethod[]): string {\n if (methods.length === 0) return \"The Backend advertises no login methods.\";\n return formatTable(\n [\"ID\", \"KIND\", \"TITLE\", \"ISSUER\"],\n methods.map((m) => [\n sanitizeForTerminal(m.id),\n m.kind,\n sanitizeForTerminal(m.title),\n m.kind === \"sso\" ? sanitizeForTerminal(m.issuer) : \"\",\n ]),\n );\n}\n\n/** Prints the login methods of the Backend at `flags.address`. Does not sign in. */\nexport async function listMethods(flags: {\n address: string;\n format?: \"text\" | \"json\";\n}): Promise<void> {\n // Only the method list is needed: no instance ID, so this works with any Backend.\n const unauth = await UnauthenticatedPlClient.build(plAddressToConfig(flags.address));\n try {\n const methods = unauth.loginMethods();\n if (flags.format === \"json\")\n outputJson(\n methods.map((m) =>\n m.kind === \"sso\"\n ? { id: m.id, kind: m.kind, title: m.title, issuer: m.issuer }\n : { id: m.id, kind: m.kind, title: m.title },\n ),\n );\n else outputText(formatLoginMethods(methods));\n } finally {\n await unauth.ll.close();\n }\n}\n\n/** Signs in to the Backend at `flags.address` and stores the session. */\nexport async function login(\n flags: LoginFlags,\n store: SessionStore = new SessionStore(),\n): Promise<void> {\n const config = plAddressToConfig(flags.address);\n // Never store or print the credentials of an address URL.\n const address = redactAddress(flags.address);\n const { unauth, instanceId: probedId } = await probeInstance(config);\n try {\n if (!(await unauth.requireAuth())) {\n outputText(`The Backend at ${address} needs no authentication. No session was stored.`);\n return;\n }\n // Backends older than v3.6.0 have no typed login methods (auth:v2) and issue tokens without\n // the instance ID. Stop before any prompt or login call.\n if (!unauth.hasCapability(\"auth:v2\")) throw new Error(OldBackendMessage);\n const instanceId = requireInstanceId(probedId);\n\n const method = pickMethod(unauth, flags, address);\n const kind: SessionLoginKind = method.kind;\n\n // Credentials in the address URL count as --user/--password, as for other commands.\n const credentials = {\n user: flags.user ?? config.user,\n password: flags.password ?? config.password,\n };\n const authInformation =\n method.kind === \"sso\"\n ? await ssoLogin(unauth, method, flags)\n : await passwordLogin(unauth, method, credentials);\n\n const token = authInformation.jwtToken;\n if (token === undefined) throw new Error(\"The Backend returned no token.\");\n const claims = parsePlToken(token);\n // Sessions are keyed by the instance ID from the ping answer. A token of another instance\n // would be stored under the wrong key, so store nothing.\n if (claims.issuer === undefined) throw new Error(OldBackendMessage);\n if (claims.issuer !== instanceId)\n throw new Error(\n `The token is for instance ${claims.issuer}, but the ping answer names ` +\n `instance ${instanceId}. No session was stored. Make sure that one Backend answers at ` +\n `${address} and try again.`,\n );\n\n const now = new Date().toISOString();\n store.put(instanceId, {\n login: claims.login,\n address,\n token,\n loginMethod: { id: method.id, kind },\n createdAt: now,\n updatedAt: now,\n });\n\n const expiry =\n claims.expiresAt === undefined ? \"\" : ` until ${new Date(claims.expiresAt).toISOString()}`;\n outputText(\n `Signed in to ${address} (instance ${instanceId}) as \"${claims.login}\". ` +\n `The session is stored${expiry} in ${store.path}.`,\n );\n } finally {\n await unauth.ll.close();\n }\n}\n\n/** Selects the login method named by `--method`. The method is never chosen implicitly, so\n * the user always knows which identity provider gets the sign-in. */\nfunction pickMethod(\n unauth: UnauthenticatedPlClient,\n flags: LoginFlags,\n address: string,\n): LoginMethod {\n const methods = unauth.loginMethods();\n if (methods.length === 0)\n throw new Error(\n \"The Backend advertises no login method that pl-cli can use. Use --user/--password per command.\",\n );\n if (flags.method === undefined)\n throw new Error(\n `Select a login method with --method <id>. Login methods of the Backend:\\n\\n` +\n `${formatLoginMethods(methods)}\\n\\n` +\n `Run: pl-cli login -a ${address} --method <id>`,\n );\n const found = methods.find((m) => m.id === flags.method);\n if (found === undefined)\n throw new Error(\n `The Backend has no login method \"${flags.method}\". Login methods of the Backend:\\n\\n` +\n formatLoginMethods(methods),\n );\n return found;\n}\n\nasync function passwordLogin(\n unauth: UnauthenticatedPlClient,\n method: LoginMethod,\n credentials: { user?: string; password?: string },\n): Promise<AuthInformation> {\n // A token method takes only the token; the login comes from the token that the Backend returns.\n const isToken = method.kind === \"token\";\n const user = isToken\n ? (credentials.user ?? \"\")\n : (credentials.user ?? (await promptLine(\"Login: \")));\n const password =\n credentials.password ??\n (await promptLine(isToken ? \"Access token: \" : \"Password: \", { hidden: true }));\n return await unauth.login(user, password, method.id);\n}\n\nasync function ssoLogin(\n unauth: UnauthenticatedPlClient,\n method: Extract<LoginMethod, { kind: \"sso\" }>,\n flags: LoginFlags,\n): Promise<AuthInformation> {\n const signal = AbortSignal.timeout((flags.timeout ?? 300) * 1000);\n const attempt = await unauth.beginSSOLogin(method.id);\n const tokenResponse = await runOidcLogin({\n method,\n nonce: attempt.nonce,\n clientSecret: attempt.clientSecret,\n signal,\n openUrl: async (url) => {\n const redirect = new URL(url).searchParams.get(\"redirect_uri\") ?? \"\";\n process.stderr.write(\n `Sign in with ${sanitizeForTerminal(method.title)} in the browser. If no browser opens, open this URL:\\n\\n` +\n ` ${url}\\n\\n` +\n `The browser must reach ${redirect} on this computer ` +\n `(when you work over SSH, forward that port).\\n` +\n `Waiting for the sign-in (up to ${flags.timeout ?? 300} s)...\\n`,\n );\n if (flags.browser !== false && !(await openInBrowser(url)))\n process.stderr.write(\"Could not open a browser; open the URL above.\\n\");\n },\n }).catch((err: unknown) => {\n if (signal.aborted)\n throw new Error(`SSO sign-in did not complete in ${flags.timeout ?? 300} s.`, { cause: err });\n throw err;\n });\n // The identity provider tokens go to the Backend only. pl-cli keeps the Platforma token.\n return await unauth.loginSSO({ tokenResponse, idP: method.id });\n}\n","import { plAddressToConfig } from \"@milaboratories/pl-client\";\nimport { probeInstance, requireInstanceId } from \"./connection\";\n\n/** Returns the instance ID of the Backend at `address`, from its ping answer. */\nexport async function instanceIdOf(address: string): Promise<string> {\n const { unauth, instanceId } = await probeInstance(plAddressToConfig(address));\n await unauth.ll.close();\n return requireInstanceId(instanceId);\n}\n\n/** Returns `instance` when given, else the instance ID of the Backend at `address`. */\nexport async function resolveInstance(flags: {\n instance?: string;\n address?: string;\n}): Promise<string> {\n if (flags.instance !== undefined) return flags.instance;\n if (flags.address !== undefined) return await instanceIdOf(flags.address);\n throw new Error(\"Give --instance <id>, or --address (or PL_ADDRESS) of a running Backend.\");\n}\n","import { Command, Option } from \"commander\";\nimport { redactAddress } from \"../address\";\nimport { addOptions, AddressOptions } from \"../cmd-opts\";\nimport { instanceIdOf } from \"../instance\";\nimport { outputText } from \"../output\";\nimport { SessionStore } from \"../session_store\";\n\nexport default function logoutCommand(): Command {\n const cmd = new Command(\"logout\").description(\n \"Remove a stored session. With --address: the current session of that Backend (found by its \" +\n \"instance ID), or the session of --login there. Without --address: the default session, \" +\n \"or with --login, the session of that login on the default session's instance. The \" +\n \"Backend keeps the session until its token expires.\",\n );\n addOptions(cmd, AddressOptions());\n cmd.addOption(\n new Option(\n \"--login <login>\",\n \"Remove the session of this login (without --address: on the default session's instance)\",\n ),\n );\n\n cmd.action(async (flags: { address?: string; login?: string }) => {\n await logout(flags);\n });\n return cmd;\n}\n\nexport async function logout(\n flags: { address?: string; login?: string },\n store: SessionStore = new SessionStore(),\n): Promise<void> {\n let instanceId: string;\n let where: string;\n if (flags.address !== undefined) {\n instanceId = await instanceIdOf(flags.address);\n where = `the Backend at ${redactAddress(flags.address)} (instance ${instanceId})`;\n } else {\n // No Backend call: the default session names its instance.\n const def = store.getDefault();\n if (def === undefined)\n throw new Error(\"No default session. Give --address (or PL_ADDRESS) of the Backend.\");\n instanceId = def.instanceId;\n where = `instance ${instanceId}`;\n }\n const login =\n flags.login ?? (flags.address === undefined ? store.getDefault()?.session.login : undefined);\n const removed = store.remove(instanceId, login);\n if (removed === undefined) {\n const which = login === undefined ? \"No current session\" : `No session of \"${login}\"`;\n outputText(`${which} is stored for ${where}.`);\n return;\n }\n outputText(`Removed the session of \"${removed.login}\" on instance ${instanceId}.`);\n}\n","import { Command, Option } from \"commander\";\nimport { redactAddress } from \"../../address\";\nimport { parsePlToken } from \"../../jwt\";\nimport { formatDate, formatTable, outputJson, outputText } from \"../../output\";\nimport { SessionStore } from \"../../session_store\";\n\nexport default function sessionListCommand(): Command {\n const cmd = new Command(\"list\").description(\n \"List stored sessions: instance ID, login, address, login method and expiry. Never prints \" +\n \"tokens. DEFAULT: the session that commands without --address use. CURRENT: the session \" +\n \"that commands use when --address selects its instance.\",\n );\n cmd.addOption(\n new Option(\"-f, --format <format>\", \"Output format\").choices([\"text\", \"json\"]).default(\"text\"),\n );\n cmd.action((flags: { format: \"text\" | \"json\" }) => {\n sessionList(flags);\n });\n return cmd;\n}\n\nexport function sessionList(\n flags: { format: \"text\" | \"json\" },\n store: SessionStore = new SessionStore(),\n): void {\n const now = Date.now();\n const rows = store.list().map(({ instanceId, current, default: isDefault, session }) => {\n let expiresAt: number | undefined;\n try {\n expiresAt = parsePlToken(session.token).expiresAt;\n } catch {\n expiresAt = undefined;\n }\n return {\n instanceId,\n default: isDefault,\n current,\n login: session.login,\n // Files written by earlier versions can hold an address with credentials.\n address: redactAddress(session.address),\n loginMethod: session.loginMethod,\n expiresAt: expiresAt === undefined ? undefined : new Date(expiresAt).toISOString(),\n expired: expiresAt !== undefined && expiresAt <= now,\n };\n });\n\n if (flags.format === \"json\") {\n outputJson(rows);\n return;\n }\n if (rows.length === 0) {\n outputText(`No stored sessions in ${store.path}.`);\n return;\n }\n outputText(\n formatTable(\n [\"DEFAULT\", \"CURRENT\", \"INSTANCE\", \"LOGIN\", \"ADDRESS\", \"METHOD\", \"EXPIRES\"],\n rows.map((r) => [\n r.default ? \"*\" : \"\",\n r.current ? \"*\" : \"\",\n r.instanceId,\n r.login,\n r.address,\n r.loginMethod === undefined ? \"\" : `${r.loginMethod.id} (${r.loginMethod.kind})`,\n r.expiresAt === undefined\n ? \"(unknown)\"\n : formatDate(new Date(r.expiresAt)) + (r.expired ? \" (expired)\" : \"\"),\n ]),\n ),\n );\n}\n","import { Command, Option } from \"commander\";\nimport { resolveInstance } from \"../../instance\";\nimport { outputText } from \"../../output\";\nimport { SessionStore } from \"../../session_store\";\n\n/** Options that name the instance: an explicit ID, or the address of a running Backend. */\nexport const InstanceOptions = (): Option[] => [\n new Option(\"--instance <id>\", \"Instance ID of the Backend (see 'pl-cli session list')\"),\n new Option(\n \"-a, --address <url>\",\n \"Address of the Backend; its ping answer gives the instance ID\",\n ).env(\"PL_ADDRESS\"),\n];\n\nexport default function sessionSelectCommand(): Command {\n const cmd = new Command(\"select\").description(\n \"Make the stored session of <login> the current session of its Backend instance. \" +\n \"Commands without credentials use the current session.\",\n );\n cmd.argument(\"<login>\", \"Login of a stored session\");\n for (const opt of InstanceOptions()) cmd.addOption(opt);\n cmd.action(async (login: string, flags: { instance?: string; address?: string }) => {\n await sessionSelect(login, flags);\n });\n return cmd;\n}\n\nexport async function sessionSelect(\n login: string,\n flags: { instance?: string; address?: string },\n store: SessionStore = new SessionStore(),\n): Promise<void> {\n const instanceId = await resolveInstance(flags);\n store.select(instanceId, login);\n outputText(`The session of \"${login}\" is now current on instance ${instanceId}.`);\n}\n","import { Command } from \"commander\";\nimport { resolveInstance } from \"../../instance\";\nimport { outputText } from \"../../output\";\nimport { SessionStore } from \"../../session_store\";\nimport { InstanceOptions } from \"./select\";\n\nexport default function sessionRemoveCommand(): Command {\n const cmd = new Command(\"remove\").description(\n \"Remove the stored session of <login>. With --instance, works when the Backend is not reachable.\",\n );\n cmd.argument(\"<login>\", \"Login of a stored session\");\n for (const opt of InstanceOptions()) cmd.addOption(opt);\n cmd.action(async (login: string, flags: { instance?: string; address?: string }) => {\n await sessionRemove(login, flags);\n });\n return cmd;\n}\n\nexport async function sessionRemove(\n login: string,\n flags: { instance?: string; address?: string },\n store: SessionStore = new SessionStore(),\n): Promise<void> {\n const instanceId = await resolveInstance(flags);\n const removed = store.remove(instanceId, login);\n if (removed === undefined)\n throw new Error(`No stored session for login \"${login}\" on instance ${instanceId}.`);\n outputText(`Removed the session of \"${login}\" on instance ${instanceId}.`);\n}\n","import type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { createPlConnection, createAdminPlConnection } from \"./connection\";\nimport { getProjectListRid, navigateToUserRoot } from \"./project_ops\";\n\n/**\n * Low-level: get an authenticated PlClient without resolving a project list.\n * Use this for commands that navigate to multiple users (e.g. admin copy-project).\n *\n * Credential precedence: `--admin-user` with `--admin-password` first, then `--user` with\n * `--password`. A login without a password (`--admin-user` or `--user` alone) selects the stored\n * session of that login. With no credentials, the current stored session of the Backend instance\n * is used. Without an address, the default stored session gives the address (not with\n * `--admin-password`). See {@link createPlConnection}.\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connectClient(flags: {\n address?: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n}): Promise<PlClient> {\n if (flags.adminPassword && !flags.adminUser) {\n throw new Error(\"--admin-password needs --admin-user (or PL_ADMIN_USER).\");\n }\n if (flags.adminUser && flags.adminPassword) {\n if (flags.address === undefined)\n throw new Error(\"Give the Backend address (--address or PL_ADDRESS) with admin credentials.\");\n return createAdminPlConnection({\n address: flags.address,\n adminUser: flags.adminUser,\n adminPassword: flags.adminPassword,\n });\n }\n if (flags.adminUser) {\n return createPlConnection({ address: flags.address, user: flags.adminUser });\n }\n return createPlConnection({\n address: flags.address,\n user: flags.user,\n password: flags.password,\n });\n}\n\n/**\n * Connect and resolve the project list for a single user.\n * In admin mode (--target-user with --admin-user + --admin-password, or with the stored session of\n * an admin user), operates on the target user's data.\n * In user mode, operates on the authenticated user's own data.\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connect(flags: {\n address?: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n targetUser?: string;\n}): Promise<{ pl: PlClient; projectListRid: SignedResourceId }> {\n const hasAdminUser = !!flags.adminUser;\n const hasAdminPassword = !!flags.adminPassword;\n const hasTarget = !!flags.targetUser;\n\n // Validate flag combinations. --target-user works with admin credentials or with a stored\n // session of an admin user; the Backend checks the role.\n if (hasTarget && !(hasAdminUser && hasAdminPassword) && flags.password !== undefined) {\n throw new Error(\n \"--target-user requires --admin-user and --admin-password, or a stored session of an admin user\",\n );\n }\n if ((hasAdminUser || hasAdminPassword) && !hasTarget) {\n throw new Error(\"--admin-user/--admin-password require --target-user for project commands\");\n }\n\n const pl = await connectClient(flags);\n\n let projectListRid: SignedResourceId;\n if (hasTarget) {\n const nav = await navigateToUserRoot(pl, flags.targetUser!);\n projectListRid = nav.projectListRid;\n } else {\n projectListRid = await getProjectListRid(pl);\n }\n\n return { pl, projectListRid };\n}\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { listProjects } from \"../../project_ops\";\nimport { formatTable, formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectListCommand(): Command {\n const cmd = new Command(\"list\").description(\"List all projects for the authenticated user.\");\n\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const projects = await listProjects(pl, projectListRid);\n\n if (flags.format === \"json\") {\n outputJson(\n projects.map((p) => ({\n id: p.id,\n rid: resourceIdToString(p.rid),\n label: p.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n } else {\n if (projects.length === 0) {\n outputText(\"No projects found.\");\n return;\n }\n\n outputText(\n formatTable(\n [\"ID\", \"RID\", \"LABEL\", \"CREATED\", \"LAST MODIFIED\"],\n projects.map((p) => [\n p.id,\n resourceIdToString(p.rid),\n p.label,\n formatDate(p.created),\n formatDate(p.lastModified),\n ]),\n ),\n );\n outputText(`\\n${projects.length} project(s)`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, getProjectInfo } from \"../../project_ops\";\nimport { formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectInfoCommand(): Command {\n const cmd = new Command(\"info\").description(\"Show detailed information about a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n const info = await getProjectInfo(pl, id, rid);\n\n if (flags.format === \"json\") {\n outputJson({\n id: info.id,\n rid: resourceIdToString(info.rid),\n label: info.label,\n schemaVersion: info.schemaVersion,\n blockCount: info.blockCount,\n blockIds: info.blockIds,\n created: info.created.toISOString(),\n lastModified: info.lastModified.toISOString(),\n });\n } else {\n outputText(`Project: ${info.label}`);\n outputText(`ID: ${info.id}`);\n outputText(`RID: ${resourceIdToString(info.rid)}`);\n outputText(`Schema: ${info.schemaVersion ?? \"(unknown)\"}`);\n outputText(`Blocks: ${info.blockCount}`);\n if (info.blockIds.length > 0) {\n for (const bid of info.blockIds) {\n outputText(` - ${bid}`);\n }\n }\n outputText(`Created: ${formatDate(info.created)}`);\n outputText(`Last Modified: ${formatDate(info.lastModified)}`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDuplicateCommand(): Command {\n const cmd = new Command(\"duplicate\").description(\n \"Duplicate a project within the same user. Auto-renames on collision by default.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"-n, --name <name>\", \"Name for the duplicate\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { rid: sourceRid } = await resolveProject(pl, projectListRid, project);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"duplicateProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, projectListRid);\n\n // Compute new label\n let newLabel: string;\n if (flags.name) {\n if (!flags.autoRename && existingLabels.includes(flags.name)) {\n throw new Error(`Project name \"${flags.name}\" already exists.`);\n }\n newLabel = existingLabels.includes(flags.name)\n ? deduplicateName(flags.name, existingLabels)\n : flags.name;\n } else {\n newLabel = deduplicateName(sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const projectResourceId = await newPrj.globalId;\n const projectId = resourceIdToString(projectResourceId);\n return { id: projectId, rid: projectResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({ id: result.id, rid: resourceIdToString(result.rid), label: result.label });\n } else {\n outputText(`Duplicated project as \"${result.label}\" (id: ${result.id})`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, renameProject } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectRenameCommand(): Command {\n const cmd = new Command(\"rename\").description(\"Rename a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.addOption(new Option(\"-n, --name <name>\", \"New name for the project\").makeOptionMandatory());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n\n await renameProject(pl, rid, flags.name);\n\n if (flags.format === \"json\") {\n outputJson({ id, rid: resourceIdToString(rid), label: flags.name });\n } else {\n outputText(`Renamed project to \"${flags.name}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, deleteProject, getProjectInfo } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDeleteCommand(): Command {\n const cmd = new Command(\"delete\").description(\n \"Delete a project. This permanently destroys all project data.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid, fieldName } = await resolveProject(pl, projectListRid, project);\n\n const info = await getProjectInfo(pl, id, rid);\n\n if (!flags.force) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\n `Delete project \"${info.label}\" (${info.blockCount} blocks)? [y/N] `,\n resolve,\n );\n });\n if (answer.toLowerCase() !== \"y\") {\n outputText(\"Aborted.\");\n return;\n }\n } finally {\n rl.close();\n }\n }\n\n await deleteProject(pl, projectListRid, fieldName);\n\n if (flags.format === \"json\") {\n outputJson({ deleted: true, id, label: info.label });\n } else {\n outputText(`Deleted project \"${info.label}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n navigateToUserRoot,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function adminCopyProjectCommand(): Command {\n const cmd = new Command(\"copy-project\").description(\n \"Copy a project from one user to another. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--source-user <user>\",\n \"Username of the source project owner\",\n ).makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--source-project <project>\", \"Source project ID or label\").makeOptionMandatory(),\n );\n cmd.option(\n \"--target-user <user>\",\n \"Username of the target user (defaults to source-user for same-user copy)\",\n );\n cmd.option(\"-n, --name <name>\", \"Name for the copied project\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const targetUser = flags.targetUser ?? flags.sourceUser;\n\n const source = await navigateToUserRoot(pl, flags.sourceUser);\n const { rid: sourceRid } = await resolveProject(\n pl,\n source.projectListRid,\n flags.sourceProject,\n );\n\n const target =\n targetUser === flags.sourceUser ? source : await navigateToUserRoot(pl, targetUser);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"adminCopyProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, target.projectListRid);\n\n let newLabel: string = flags.name ?? sourceLabel;\n\n if (existingLabels.includes(newLabel)) {\n if (!flags.autoRename) {\n throw new Error(`Project name \"${newLabel}\" already exists for target user.`);\n }\n newLabel = deduplicateName(flags.name ?? sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(target.projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const prjResourceId = await newPrj.globalId;\n const prjId = resourceIdToString(prjResourceId);\n return { id: prjId, rid: prjResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({\n id: result.id,\n rid: resourceIdToString(result.rid),\n label: result.label,\n sourceUser: flags.sourceUser,\n targetUser,\n });\n } else {\n outputText(\n `Copied project from ${flags.sourceUser} to ${targetUser} as \"${result.label}\" (id: ${result.id}, rid: ${resourceIdToString(result.rid)})`,\n );\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { isPermissionDenied } from \"@milaboratories/pl-client\";\nimport { Command } from \"commander\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson, outputText, outputCsv } from \"../../output\";\n\nexport default function adminUserListCommand(): Command {\n const cmd = new Command(\"user-list\").description(\n \"List all known users' logins from a live server. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"csv\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n let users;\n try {\n users = await pl.listUsers();\n } catch (err) {\n if (isPermissionDenied(err))\n throw new Error(\n \"The server does not let this user list users. \" +\n \"Check the server option '--show-user-list-to' and the role of the user.\",\n { cause: err },\n );\n throw err;\n }\n const logins = users.map((u) => u.login).sort();\n if (flags.format === \"json\") outputJson(logins);\n else if (flags.format === \"text\") outputText(logins.join(\"\\n\"));\n else\n outputCsv(\n [\"login\"],\n logins.map((l) => [l]),\n );\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connectClient } from \"../../base_command\";\nimport { authenticatedLogin } from \"../../connection\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n ensureUserProjectList,\n listProjectIdentities,\n moveProjects,\n openUserRoot,\n} from \"../../project_ops\";\nimport type { MovedProject, ProjectIdentityWithLabel } from \"../../project_ops\";\nimport { formatTable, outputJson, outputText } from \"../../output\";\n\nexport default function adminDeleteUserCommand(): Command {\n const cmd = new Command(\"delete-user\").description(\n \"Delete a user account. Optionally re-homes the user's projects to another user first. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\"<user>\", \"Username of the account to delete\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--move-projects-to <user>\",\n \"Re-home the deleted user's projects to this user before deleting the account\",\n ),\n );\n cmd.addOption(\n new Option(\n \"--delete-projects\",\n \"Delete the user's projects along with the account, losing their data\",\n ),\n );\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (user: string, flags) => {\n // The two modes are alternatives, not a combination: one keeps the projects, the other\n // destroys them, and a request for both says nothing about which was meant.\n if (flags.moveProjectsTo && flags.deleteProjects) {\n throw new Error(\"--move-projects-to and --delete-projects are mutually exclusive\");\n }\n if (flags.moveProjectsTo === user) {\n throw new Error(\"--move-projects-to must name a different user than the one being deleted\");\n }\n // Caught here as well as server-side, where it is authoritative: the operator gets the reason\n // instead of a failure from whichever lookup happens to run first.\n if (flags.adminUser === user) {\n throw new Error(\n `Refusing to delete \"${user}\" — it is the account these credentials authenticate as.`,\n );\n }\n\n const pl = await connectClient(flags);\n try {\n // The same check for a stored session, whose login is known only after connecting.\n if (authenticatedLogin(pl) === user) {\n throw new Error(\n `Refusing to delete \"${user}\" — it is the account this session authenticates as.`,\n );\n }\n const source = await openUserRoot(pl, user);\n // No project list means the account never opened the app, so it owns nothing — a state to\n // delete straight through, not to fail on.\n const projects =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n\n // Neither mode given while the account still owns projects: refuse rather than pick. Both\n // defaults are wrong to assume — one silently destroys data, the other silently hands it to\n // someone. An account with no projects has nothing to decide about, so it just proceeds.\n if (projects.length > 0 && !flags.moveProjectsTo && !flags.deleteProjects) {\n throw new Error(\n `User \"${user}\" owns ${projects.length} project(s). Pass --move-projects-to <user> to ` +\n \"re-home them, or --delete-projects to delete them with the account.\",\n );\n }\n\n const confirmed = await confirmDeletion(user, projects, flags);\n if (!confirmed) {\n outputText(\"Aborted.\");\n return;\n }\n\n let moved: MovedProject[] = [];\n if (flags.moveProjectsTo && projects.length > 0) {\n const target = await openUserRoot(pl, flags.moveProjectsTo);\n // Created if the target has none, so re-homing to a user who has never opened the app\n // works rather than failing halfway with the account still present.\n const targetList = await ensureUserProjectList(pl, target.userRoot);\n moved = await moveProjects(pl, source.projectListRid!, targetList);\n }\n\n // deleteUser takes the root and everything still attached to it. The listing, the prompt and\n // the move each ran in an earlier transaction, so re-read: a project attached since then would\n // be destroyed without ever being reviewed.\n const remaining =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n assertProjectsAccountedFor(user, flags, projects, remaining);\n\n const report = await pl.deleteUser(user);\n\n if (flags.format === \"json\") {\n outputJson({\n deleted: true,\n user,\n movedTo: flags.moveProjectsTo ?? null,\n movedProjects: moved,\n deletedProjects: flags.moveProjectsTo ? [] : remaining.map((p) => p.label),\n userRootId: report.userRootId === undefined ? null : report.userRootId.toString(),\n userRootDeleted: report.userRootDeleted,\n revokedGrants: report.revokedGrants,\n removedIdentityIndexEntries: report.removedIdentityIndexEntries,\n });\n } else {\n outputText(renderResult(user, flags.moveProjectsTo, moved, remaining));\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/**\n * Refuses while the root holds a project the operator never agreed to lose — attached after the\n * listing, or left behind by the move.\n *\n * A last read, not a lock: it closes the prompt-sized window, not the round trip that follows.\n */\nfunction assertProjectsAccountedFor(\n user: string,\n flags: { moveProjectsTo?: string },\n approved: ProjectIdentityWithLabel[],\n remaining: ProjectIdentityWithLabel[],\n): void {\n if (flags.moveProjectsTo) {\n if (remaining.length === 0) return;\n throw new Error(\n `User \"${user}\" still owns ${remaining.length} project(s) after the move: ` +\n `${remaining.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"the projects were attached while the move ran. Re-run the command to move them too.\",\n );\n }\n\n const approvedIds = new Set(approved.map((p) => p.id));\n const unapproved = remaining.filter((p) => !approvedIds.has(p.id));\n if (unapproved.length === 0) return;\n throw new Error(\n `User \"${user}\" gained ${unapproved.length} project(s) since the list you confirmed: ` +\n `${unapproved.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"deleting it now would destroy them unreviewed. Re-run the command to see the current list.\",\n );\n}\n\n/** Asks the operator to confirm, naming the affected projects and their fate. */\nasync function confirmDeletion(\n user: string,\n projects: ProjectIdentityWithLabel[],\n flags: { moveProjectsTo?: string; force?: boolean },\n): Promise<boolean> {\n if (flags.force) return true;\n\n const fate = flags.moveProjectsTo\n ? `${projects.length} project(s) will move to \"${flags.moveProjectsTo}\"`\n : projects.length > 0\n ? `${projects.length} project(s) will be PERMANENTLY DELETED`\n : \"the account owns no projects\";\n\n process.stderr.write(`Delete user \"${user}\"? ${fate}.\\n`);\n if (projects.length > 0) {\n process.stderr.write(projects.map((p) => ` - ${p.label}`).join(\"\\n\") + \"\\n\");\n }\n\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", resolve);\n });\n return answer.toLowerCase() === \"y\";\n } finally {\n rl.close();\n }\n}\n\nfunction renderResult(\n user: string,\n movedTo: string | undefined,\n moved: MovedProject[],\n projects: ProjectIdentityWithLabel[],\n): string {\n const lines: string[] = [];\n\n if (movedTo) {\n if (moved.length > 0) {\n lines.push(`Moved ${moved.length} project(s) from ${user} to ${movedTo}:`);\n lines.push(\n formatTable(\n [\"id\", \"name\", \"name in target\"],\n moved.map((p) => [p.id, p.sourceLabel, p.targetLabel]),\n ),\n );\n } else {\n lines.push(`User ${user} had no projects to move.`);\n }\n } else if (projects.length > 0) {\n lines.push(`Deleted ${projects.length} project(s) belonging to ${user}:`);\n lines.push(projects.map((p) => ` - ${p.label}`).join(\"\\n\"));\n }\n\n lines.push(`Deleted user \"${user}\".`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { InstanceStatsContextTypeName, parseInstanceStats } from \"@milaboratories/pl-middle-layer\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson } from \"../../output\";\n\nexport default function adminInstanceStatsCommand(): Command {\n const cmd = new Command(\"instance-stats\").description(\"Show the instance statistics as JSON.\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const [context] = await pl.listSharedResourcesByType(InstanceStatsContextTypeName);\n if (context === undefined) throw new Error(\"The instance has no instance statistics.\");\n const kvs = await pl.withReadTx(\"instanceStats\", (tx) => tx.listKeyValuesString(context));\n outputJson(parseInstanceStats(kvs));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import {\n asSignedResourceId,\n createSignedResourceId,\n isLocalResourceId,\n resourceIdFromString,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\n\n/**\n * Admin and controller roles do not need resource signatures: an ID without a signature\n * is accepted by the backend for these roles.\n */\nexport function parseResourceId(raw: string): SignedResourceId {\n const str = raw.trim();\n if (str.includes(\"|\")) return asSignedResourceId(str);\n\n let id: bigint | undefined = resourceIdFromString(str);\n if (id === undefined && /^\\d+$/.test(str)) id = BigInt(str);\n if (id === undefined || id === 0n || isLocalResourceId(id))\n throw new Error(`not a global resource ID: ${raw}`);\n\n return createSignedResourceId(id);\n}\n","import { once } from \"node:events\";\nimport { Command, InvalidArgumentError, Option } from \"commander\";\nimport {\n isNotNullSignedResourceId,\n resourceIdToString,\n resourceType,\n resourceTypeToString,\n type FieldData,\n type KeyValue,\n type OptionalSignedResourceId,\n type ResourceData,\n type ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { parseResourceId } from \"../../resource_id\";\n\nexport default function maintenanceListResourcesCommand(): Command {\n const cmd = new Command(\"list-resources\").description(\n \"List resources of one type as JSON lines, in ascending order of resource ID. \" +\n \"Resource data and key-value values are printed as JSON when they are valid JSON, \" +\n 'as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. ' +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"--type <name:version>\", \"Resource type to list (e.g. 'Blob/work:1')\")\n .argParser(parseResourceTypeArg)\n .makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--limit <n>\", \"Maximum number of resources to list. 0 lists all resources\")\n .argParser(parseNonNegativeInt)\n .default(0),\n );\n cmd.addOption(\n new Option(\n \"--after <resource-id>\",\n \"List only resources with IDs greater than this ID. \" +\n \"To get the next page, give the ID of the last resource of the previous page\",\n ).argParser(parseResourceId),\n );\n cmd.option(\n \"--load-fields\",\n \"Load the fields and the error of each resource ('fields' and 'error' keys)\",\n false,\n );\n cmd.option(\"--load-kv\", \"Load the key-value entries of each resource ('kv' key)\", false);\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const resources = await pl.withReadTx(\"listResources\", async (tx) => {\n const list = await tx.listResourcesByType(flags.type, {\n limit: flags.limit,\n after: flags.after,\n loadFields: flags.loadFields,\n });\n return await Promise.all(\n list.map(async (resource) => ({\n resource,\n kv: flags.loadKv ? await tx.listKeyValues(resource.id) : undefined,\n })),\n );\n });\n\n for (const { resource, kv } of resources) {\n const line = JSON.stringify(toJson(resource, flags.loadFields, kv)) + \"\\n\";\n // Wait for a slow reader: else the output collects in memory a second time.\n if (!process.stdout.write(line)) await once(process.stdout, \"drain\");\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\nfunction toJson(\n r: ResourceData,\n withFields: boolean,\n kv: KeyValue[] | undefined,\n): Record<string, unknown> {\n return {\n id: resourceIdToString(r.id),\n type: resourceTypeToString(r.type),\n kind: r.kind,\n originalId: optionalIdToString(r.originalResourceId),\n inputsLocked: r.inputsLocked,\n outputsLocked: r.outputsLocked,\n ready: r.resourceReady,\n final: r.final,\n data: r.data === undefined || r.data.length === 0 ? null : decodeBytes(r.data),\n // The backend sends the resource error as a field: without fields it is not known.\n ...(withFields\n ? { error: optionalIdToString(r.error), fields: r.fields.map(fieldToJson) }\n : {}),\n ...(kv === undefined\n ? {}\n : { kv: Object.fromEntries(kv.map((e) => [e.key, decodeBytes(e.value)])) }),\n };\n}\n\nfunction fieldToJson(f: FieldData): Record<string, unknown> {\n return {\n name: f.name,\n type: f.type,\n status: f.status,\n value: optionalIdToString(f.value),\n error: optionalIdToString(f.error),\n valueIsFinal: f.valueIsFinal,\n };\n}\n\nfunction optionalIdToString(id: OptionalSignedResourceId): string | null {\n return isNotNullSignedResourceId(id) ? resourceIdToString(id) : null;\n}\n\n/** JSON value when the bytes are valid JSON, text when valid UTF-8, {\"base64\": ...} otherwise. */\nfunction decodeBytes(bytes: Uint8Array): unknown {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return { base64: Buffer.from(bytes).toString(\"base64\") };\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseResourceTypeArg(value: string): ResourceType {\n const sep = value.lastIndexOf(\":\");\n if (sep <= 0 || sep === value.length - 1)\n throw new InvalidArgumentError(`expected <name>:<version>, e.g. 'Blob/work:1': ${value}`);\n return resourceType(value.slice(0, sep), value.slice(sep + 1));\n}\n\nfunction parseNonNegativeInt(value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0)\n throw new InvalidArgumentError(`not a non-negative integer: ${value}`);\n return n;\n}\n","import { Command, Option } from \"commander\";\nimport { isNotNullSignedResourceId, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputText } from \"../../output\";\nimport { parseResourceId } from \"../../resource_id\";\n\nconst DefaultErrorMessage =\n \"Manual error set by administrator to trigger blocks re-run. \" +\n \"Run block once again to get rid of it.\";\n\nexport default function maintenanceSetResourceErrorCommand(): Command {\n const cmd = new Command(\"set-resource-error\").description(\n \"Put an error on one or more resources in a single transaction. \" +\n \"Resources that already have an error are skipped. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\n \"<resource-id...>\",\n \"Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, \" +\n \"or as signed IDs (<decimal ID>|<signature hex>)\",\n );\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"-m, --error-message <message>\", \"Error message to put on the resources\").default(\n DefaultErrorMessage,\n ),\n );\n cmd.option(\n \"--skip-missing\",\n \"Skip resources that do not exist instead of failing the whole transaction\",\n false,\n );\n\n cmd.action(async (rawIds: string[], flags) => {\n // Parse all IDs before the connection, so that a typo does not leave a half-done job.\n const ids = rawIds.map(parseResourceId);\n\n const pl = await connectClient(flags);\n try {\n const result = await pl.withWriteTx(\"setResourceError\", async (tx) => {\n const found = await Promise.all(\n ids.map(async (id) => ({\n id,\n data: flags.skipMissing\n ? await tx.getResourceDataIfExists(id, true)\n : await tx.getResourceData(id, true, true),\n })),\n );\n\n const missing = found.filter((r) => r.data === undefined).map((r) => r.id);\n const resources = found.flatMap((r) => (r.data === undefined ? [] : [r.data]));\n const targets = resources.filter((r) => !isNotNullSignedResourceId(r.error));\n const skipped = resources.filter((r) => isNotNullSignedResourceId(r.error));\n\n if (targets.length > 0) {\n // One error resource for all targets: the backend links it to each target separately.\n const error = tx.createError(flags.errorMessage);\n for (const r of targets) tx.setResourceError(r.id, error);\n await tx.commit();\n }\n\n return { targets, skipped, missing };\n });\n\n for (const id of result.missing)\n outputText(`skipped ${resourceIdToString(id)}: resource does not exist`);\n for (const r of result.skipped)\n outputText(`skipped ${resourceIdToString(r.id)}: resource already has an error`);\n for (const r of result.targets) outputText(`error set ${resourceIdToString(r.id)}`);\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { isUnauthenticated } from \"@milaboratories/pl-client\";\nimport {\n SessionRequiredError,\n resetUsedSession,\n sessionRefusedMessage,\n usedSession,\n} from \"./connection\";\nimport loginCommand from \"./cmd/login\";\nimport logoutCommand from \"./cmd/logout\";\nimport sessionListCommand from \"./cmd/session/list\";\nimport sessionSelectCommand from \"./cmd/session/select\";\nimport sessionRemoveCommand from \"./cmd/session/remove\";\nimport projectListCommand from \"./cmd/project/list\";\nimport projectInfoCommand from \"./cmd/project/info\";\nimport projectDuplicateCommand from \"./cmd/project/duplicate\";\nimport projectRenameCommand from \"./cmd/project/rename\";\nimport projectDeleteCommand from \"./cmd/project/delete\";\nimport adminCopyProjectCommand from \"./cmd/admin/copy-project\";\nimport adminUserListCommand from \"./cmd/admin/user-list\";\nimport adminDeleteUserCommand from \"./cmd/admin/delete-user\";\nimport adminInstanceStatsCommand from \"./cmd/admin/instance-stats\";\nimport maintenanceListResourcesCommand from \"./cmd/maintenance/list-resources\";\nimport maintenanceSetResourceErrorCommand from \"./cmd/maintenance/set-resource-error\";\n\nexport function buildProgram(): Command {\n const program = new Command();\n program.name(\"pl-cli\").description(\"Platforma command-line client\");\n program.addHelpText(\n \"after\",\n `\nAuthentication, in order of precedence:\n 1. --admin-user with --admin-password (admin commands), or --user with --password\n (PL_ADMIN_USER/PL_ADMIN_PASSWORD, PL_USER/PL_PASSWORD): sign in with them.\n 2. --admin-user or --user without a password: the stored session of that login.\n 3. No credentials: the current stored session of the Backend instance.\nWithout --address (and PL_ADDRESS), commands use the default session: its stored\naddress, if the Backend there still has the same instance ID. \"pl-cli login\" and\n\"pl-cli session select\" set the default session.\nCredentials in the address URL (http://user:password@host) count as --user/--password.\nEnvironment variables count as the flags: a PL_USER or PL_ADMIN_USER in your shell\nselects that login's stored session, and PL_USER with PL_PASSWORD bypasses the\nstored sessions. pl-cli prints a note when it takes credentials from the environment.\nSign in once with \"pl-cli login\" (needs Backend v3.6.0 or newer; on older Backends\ngive --user/--password with each command). Sessions are keyed by the instance ID from the\nping answer of the Backend, not by its address. They are stored in\n~/.platforma/pl-cli.sessions (override with PL_CLI_SESSIONS_FILE).`,\n );\n program.hook(\"preAction\", (_program, actionCommand) => noteCredentialsFromEnv(actionCommand));\n\n program.addCommand(loginCommand());\n program.addCommand(logoutCommand());\n\n const session = new Command(\"session\").description(\n \"Manage stored sessions (one file, sessions keyed by Backend instance ID)\",\n );\n session.addCommand(sessionListCommand());\n session.addCommand(sessionSelectCommand());\n session.addCommand(sessionRemoveCommand());\n program.addCommand(session);\n\n const project = new Command(\"project\").description(\"Manage projects\");\n project.addCommand(projectListCommand());\n project.addCommand(projectInfoCommand());\n project.addCommand(projectDuplicateCommand());\n project.addCommand(projectRenameCommand());\n project.addCommand(projectDeleteCommand());\n program.addCommand(project);\n\n const admin = new Command(\"admin\").description(\n \"Admin operations (requires controller credentials or an admin's stored session)\",\n );\n admin.addCommand(adminCopyProjectCommand());\n admin.addCommand(adminUserListCommand());\n admin.addCommand(adminDeleteUserCommand());\n admin.addCommand(adminInstanceStatsCommand());\n program.addCommand(admin);\n\n const maintenance = new Command(\"maintenance\").description(\n \"Low-level server state repair (requires admin/controller credentials or an admin's stored session)\",\n );\n maintenance.addCommand(maintenanceListResourcesCommand());\n maintenance.addCommand(maintenanceSetResourceErrorCommand());\n program.addCommand(maintenance);\n\n return program;\n}\n\nconst credentialEnv: Record<string, string> = {\n user: \"PL_USER\",\n password: \"PL_PASSWORD\",\n adminUser: \"PL_ADMIN_USER\",\n adminPassword: \"PL_ADMIN_PASSWORD\",\n};\n\n/** Prints one line when credentials come from environment variables: they change which login\n * a command uses, and the user can forget that they are set. */\nfunction noteCredentialsFromEnv(cmd: Command): void {\n const fromEnv = Object.entries(credentialEnv)\n .filter(([option]) => cmd.getOptionValueSource(option) === \"env\")\n .map(([, env]) => env);\n if (fromEnv.length > 0)\n process.stderr.write(`note: using credentials from the environment: ${fromEnv.join(\", \")}\\n`);\n}\n\nexport async function run(argv: string[] = process.argv): Promise<void> {\n resetUsedSession();\n try {\n await buildProgram().parseAsync(argv);\n } catch (err) {\n // A stored token can pass the local expiry check and still be refused later, for example\n // when the session was closed on the Backend. Tell the user to sign in again.\n const session = usedSession();\n if (session !== undefined && !(err instanceof SessionRequiredError) && isUnauthenticated(err))\n throw new Error(sessionRefusedMessage(session, \"refused\"), { cause: err });\n throw err;\n }\n}\n"],"m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EAAY,WAAWjC,GAAgC,CAAC,GACxDiC,EAAY,WAAWX,GAAmC,CAAC,GAC3DO,EAAQ,WAAWI,CAAW,GAEvBJ;AACT;AAEA,IAAMK,KAAwC;CAC5C,MAAM;CACN,UAAU;CACV,WAAW;CACX,eAAe;AACjB;AAIA,SAASJ,GAAuB,GAAoB;CAClD,IAAMK,IAAU,OAAO,QAAQD,EAAa,CAAC,CAC1C,QAAQ,CAAC5O,OAAYF,EAAI,qBAAqBE,CAAM,MAAM,KAAK,CAAC,CAChE,KAAK,GAAG8O,OAASA,CAAG;CACvB,AAAID,EAAQ,SAAS,KACnB,QAAQ,OAAO,MAAM,iDAAiDA,EAAQ,KAAK,IAAI,EAAE,GAAG;AAChG;AAEA,eAAsBE,GAAI,IAAiB,QAAQ,MAAqB;CACtE,EAAiB;CACjB,IAAI;EACF,MAAMT,EAAa,CAAC,CAAC,WAAWU,CAAI;CACtC,SAAS5K,GAAK;EAGZ,IAAMyD,IAAUpK,EAAY;EAG5B,MAFIoK,MAAY,KAAA,KAAa,EAAEzD,aAAepG,MAAyBiR,GAAkB7K,CAAG,IAChF,MAAMxF,GAAsBiJ,GAAS,SAAS,GAAG,EAAE,OAAOzD,EAAI,CAAC,IACrEA;CACR;AACF"}
@@ -0,0 +1,21 @@
1
+ import { Command } from 'commander';
2
+ import { LoginMethod } from '@milaboratories/pl-client';
3
+ import { SessionStore } from '../session_store';
4
+ export default function loginCommand(): Command;
5
+ export interface LoginFlags {
6
+ address: string;
7
+ user?: string;
8
+ password?: string;
9
+ method?: string;
10
+ browser?: boolean;
11
+ timeout?: number;
12
+ }
13
+ /** Formats login methods as a table: ID, KIND, TITLE, ISSUER (SSO only). */
14
+ export declare function formatLoginMethods(methods: LoginMethod[]): string;
15
+ /** Prints the login methods of the Backend at `flags.address`. Does not sign in. */
16
+ export declare function listMethods(flags: {
17
+ address: string;
18
+ format?: "text" | "json";
19
+ }): Promise<void>;
20
+ /** Signs in to the Backend at `flags.address` and stores the session. */
21
+ export declare function login(flags: LoginFlags, store?: SessionStore): Promise<void>;
@@ -0,0 +1,7 @@
1
+ import { Command } from 'commander';
2
+ import { SessionStore } from '../session_store';
3
+ export default function logoutCommand(): Command;
4
+ export declare function logout(flags: {
5
+ address?: string;
6
+ login?: string;
7
+ }, store?: SessionStore): Promise<void>;
@@ -0,0 +1,6 @@
1
+ import { Command } from 'commander';
2
+ import { SessionStore } from '../../session_store';
3
+ export default function sessionListCommand(): Command;
4
+ export declare function sessionList(flags: {
5
+ format: "text" | "json";
6
+ }, store?: SessionStore): void;
@@ -0,0 +1,7 @@
1
+ import { Command } from 'commander';
2
+ import { SessionStore } from '../../session_store';
3
+ export default function sessionRemoveCommand(): Command;
4
+ export declare function sessionRemove(login: string, flags: {
5
+ instance?: string;
6
+ address?: string;
7
+ }, store?: SessionStore): Promise<void>;
@@ -0,0 +1,9 @@
1
+ import { Command, Option } from 'commander';
2
+ import { SessionStore } from '../../session_store';
3
+ /** Options that name the instance: an explicit ID, or the address of a running Backend. */
4
+ export declare const InstanceOptions: () => Option[];
5
+ export default function sessionSelectCommand(): Command;
6
+ export declare function sessionSelect(login: string, flags: {
7
+ instance?: string;
8
+ address?: string;
9
+ }, store?: SessionStore): Promise<void>;
@@ -2,11 +2,16 @@ import { Command, Option } from 'commander';
2
2
  import { OutputFormat } from './output';
3
3
  /** Add one or more groups of options to a command, preserving group order. */
4
4
  export declare function addOptions(cmd: Command, ...optionGroups: Option[][]): Command;
5
- /** Server address only (for commands with a fixed output format). */
6
- export declare const AddressOptions: () => Option[];
5
+ /** Server address. Optional by default: without it, commands use the address of the default
6
+ * stored session (see `pl-cli session select`). */
7
+ export declare const AddressOptions: (opts?: {
8
+ required?: boolean;
9
+ }) => Option[];
7
10
  export declare const GlobalOptions: (formatDefault?: OutputFormat, allowedFormats?: OutputFormat[]) => Option[];
8
11
  export declare const UserAuthOptions: () => Option[];
9
- /** Admin credentials only (for purely admin commands like copy-project). */
12
+ /** Admin credentials only (for purely admin commands like copy-project).
13
+ * Without them, the command uses the stored session (see `pl-cli login`); the Backend checks
14
+ * that its user has the admin role. */
10
15
  export declare const AdminAuthOptions: () => Option[];
11
16
  /** Admin credentials + target user (for regular commands that can optionally operate on another user). */
12
17
  export declare const AdminTargetOptions: () => Option[];
@@ -1,15 +1,71 @@
1
- import { PlClient } from '@milaboratories/pl-client';
1
+ import { PlClient, UnauthenticatedPlClient, PlClientConfig } from '@milaboratories/pl-client';
2
+ import { SessionStore } from './session_store';
2
3
  export interface PlConnectionOptions {
3
- address: string;
4
+ /** Backend address. Absent: the stored address of the default session (see `pl-cli session
5
+ * select`), which is used only if the Backend there still has the same instance ID. */
6
+ address?: string;
4
7
  user?: string;
5
8
  password?: string;
9
+ /** Store of sessions. Default: the store at the default path. `null`: do not use stored
10
+ * sessions; the connection then needs credentials (as before stored sessions existed). */
11
+ sessionStore?: SessionStore | null;
6
12
  }
7
13
  export interface AdminConnectionOptions {
8
14
  address: string;
9
15
  adminUser: string;
10
16
  adminPassword: string;
11
17
  }
12
- /** Creates an authenticated PlClient from address + credentials. */
18
+ /** The stored session that a connection uses. */
19
+ export interface UsedSession {
20
+ instanceId: string;
21
+ login: string;
22
+ }
23
+ /** Thrown when a stored session cannot be used. The message tells the user what to do. */
24
+ export declare class SessionRequiredError extends Error {
25
+ name: string;
26
+ }
27
+ /** The login that the client is signed in as, if it is known. */
28
+ export declare function authenticatedLogin(pl: PlClient): string | undefined;
29
+ /** The stored session that the last connection of this process used, if any. */
30
+ export declare function usedSession(): UsedSession | undefined;
31
+ /** Forgets the stored session that the last connection used. Call it before a new command. */
32
+ export declare function resetUsedSession(): void;
33
+ /** Opens an unauthenticated client and returns it with the instance ID from the ping answer.
34
+ * The instance ID is `undefined` for a Backend that does not return one (older than v3.0.4);
35
+ * call {@link requireInstanceId} where a stored session is read or written.
36
+ * The caller must close the client: `await unauth.ll.close()`. */
37
+ export declare function probeInstance(config: PlClientConfig | string): Promise<{
38
+ unauth: UnauthenticatedPlClient;
39
+ instanceId: string | undefined;
40
+ }>;
41
+ /** Stored sessions are keyed by the instance ID; a Backend without one cannot have them. */
42
+ export declare function requireInstanceId(instanceId: string | undefined): string;
43
+ /**
44
+ * Creates an authenticated PlClient.
45
+ *
46
+ * Credential precedence (`user` and `password` default to the credentials in the address URL):
47
+ * 1. The Backend requires no authentication: anonymous access.
48
+ * 2. `user` and `password` are both given: sign in with them. Stored sessions are not used.
49
+ * 3. Only `user` is given: the stored session of that login on this Backend instance.
50
+ * 4. Nothing is given: the current stored session of this Backend instance.
51
+ *
52
+ * With `sessionStore: null`, rules 3 and 4 do not apply.
53
+ *
54
+ * Without `address`, the connection goes to the stored address of the default session, and
55
+ * rules 3 and 4 use the instance of that session (rule 4: the default session itself). If the
56
+ * Backend at that address has another instance ID (an SSH tunnel now points elsewhere), the
57
+ * connection stops before it sends a token.
58
+ *
59
+ * The instance comes from the ping answer of the Backend at `address`, so a session follows
60
+ * its Backend, not its address.
61
+ */
13
62
  export declare function createPlConnection(opts: PlConnectionOptions): Promise<PlClient>;
14
63
  /** Creates a PlClient with admin/controller credentials. */
15
64
  export declare function createAdminPlConnection(opts: AdminConnectionOptions): Promise<PlClient>;
65
+ /** Minimum Backend version for `pl-cli login` and stored sessions: since this version the
66
+ * Backend writes its instance ID into the `iss` claim of the tokens it issues. */
67
+ export declare const MinSessionBackendVersion = "3.6.0";
68
+ /** Message for a token without `iss`: the Backend is too old for stored sessions. */
69
+ export declare const OldBackendMessage: string;
70
+ /** Message for a Backend that refused or expired a stored session. */
71
+ export declare function sessionRefusedMessage(s: UsedSession, reason: "expired" | "refused"): string;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { b as createAdminPlConnection, x as createPlConnection, o as deduplicateName, s as deleteProject, c as duplicateProject, t as formatDate, n as formatTable, u as getExistingLabelsInTx, d as getProjectInfo, f as getProjectListRid, m as listProjects, g as navigateToUserRoot, i as outputJson, a as outputText, v as renameProject, y as resolveProject } from "./output-D41Wn0wM.js";
1
+ export { S as SessionRequiredError, j as SessionStore, M as SessionsFileEnv, C as authenticatedLogin, w as createAdminPlConnection, T as createPlConnection, t as deduplicateName, N as defaultSessionsPath, n as deleteProject, r as duplicateProject, h as formatDate, g as formatTable, a as getExistingLabelsInTx, o as getProjectInfo, s as getProjectListRid, l as listProjects, d as navigateToUserRoot, v as outputJson, y as outputText, p as renameProject, m as resolveProject } from "./project_ops-CHhJu5k5.js";