Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
LibMeshCtrl
https://github.com/ylianst/libmeshctrl
Admin
API for remotely interacting with a MeshCentral server instance.
Tokens:
73,853
Snippets:
490
Trust Score:
9.6
License:
Apache-2.0
Update:
4 weeks ago
Context
Chat
Benchmark
82.89
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Session instantiation examples (minimal and full featured) Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/configuration.md Two usage examples for creating a Session. The minimal example uses Session.create with just user and password. The full example uses the new Session constructor with all options and requires awaiting session.initialized. Standalone instantiation requires awaiting session.initialized; Session.create does this for you. ```javascript // Minimal const s = await Session.create("wss://mesh.example.com", {user: "admin", password: "pw"}); ``` ```javascript // Full featured const s = new Session("ws://mesh.example.com", { user: "admin", domain: "corp", password: "pw", proxy: "proxy.example.com:8080", token: "abc123", ignoreSSL: true }); await s.initialized; ``` -------------------------------- ### Add device share example with error handling Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shares.md Example of adding a terminal share and handling an error when end time is not ahead of start time. ```javascript const share = await session.add_device_share("node//abc", "consultant", { type: SHARINGTYPE.terminal, start: Date.now(), duration: 2 * 60 * 60 }); // Error handling try { await session.add_device_share("node//abc", "x", { start: Date.now() + 60000, duration: 30 }); } catch (e) { console.log(e.message); // "End time must be ahead of start time" } ``` -------------------------------- ### add_user usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-users.md Example of calling add_user with options for email, realname, and rights. Returns a Promise that resolves to true on success. ```javascript const ok = await session.add_user("jdoe", "hunter2", { email: "jdoe@example.com", realname: "Jane Doe", rights: USERRIGHTS.manageusers | USERRIGHTS.fullrights }); ``` -------------------------------- ### list_devices usage examples Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-devices.md Example calls to list_devices: without options returns all devices, with meshid restricts to a mesh, and with details=true fetches full device details. ```javascript const all = await session.list_devices(); const inMesh = await session.list_devices({ meshid: "mesh//abc" }); const detailed = await session.list_devices({ details: true }); ``` -------------------------------- ### List device shares example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shares.md Example usage of list_device_shares to retrieve and log shares for a node. ```javascript const shares = await session.list_device_shares("node//abc"); for (const s of shares) console.log(s.guestname, s.end); ``` -------------------------------- ### add_users_to_user_group usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-groups.md Example call to add a user to a user group. Uses the session object and awaits the result. The example adds user 'user//admin//jdoe' to group 'ugrp//engineering'. ```javascript const added = await session.add_users_to_user_group(["user//admin//jdoe"], "ugrp//engineering"); ``` -------------------------------- ### list_users usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-users.md Shows how to call list_users, iterate over returned users, and handle failures with a timeout and error type check. ```js const users = await session.list_users(); for (const u of users) console.log(u._id, u.name); // Failure handling try { await session.list_users(5000); } catch (e) { console.log(e.type === ERRORS.ServerError.type, e.message); } ``` -------------------------------- ### edit_device usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-devices.md Example usage of edit_device. Updates the device name to "web-01", sets the icon to ICON.server, and assigns tags ["prod", "eu"]. ```javascript await session.edit_device("node//abc", { name: "web-01", icon: ICON.server, tags: ["prod", "eu"] }); ``` -------------------------------- ### Using mkdir with error handling Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-files.md Example usage of the mkdir method, including error handling. The try/catch block demonstrates catching a ServerError when the operation fails, such as when lacking permissions. ```javascript await files.mkdir("/home/user/newdir"); // error handling try { await files.mkdir("/root/noperm"); } catch (e) { /* ServerError */ } ``` -------------------------------- ### list_user_sessions usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-users.md Shows a simple call to list_user_sessions to retrieve connected user sessions. ```js const sessions = await session.list_user_sessions(); ``` -------------------------------- ### add_users_to_device_group usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-groups.md Example call to add_users_to_device_group granting remotecontrol and agentconsole rights to user 'jdoe' in mesh 'mesh//abc'. Checks the per-user result to confirm success before proceeding. ```javascript const results = await session.add_users_to_device_group(["jdoe"], "mesh//abc", { rights: MESHRIGHTS.remotecontrol | MESHRIGHTS.agentconsole }); if (results["jdoe"].success) { /* granted */ } ``` -------------------------------- ### Using ls to list directory contents Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-files.md Example usage of the ls method. Creates a file explorer session and lists the contents of /home/user. ```javascript const files = await session.file_explorer("node//abc"); const listing = await files.ls("/home/user"); ``` -------------------------------- ### Using _SmartShell with session.smart_shell() Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shells.md Example usage of _SmartShell obtained via Session#smart_shell(). Creates a smart shell with a regex for the prompt, sends a command, and logs the output. ```javascript const shell = await session.smart_shell("node//abc", />\s*$/); const out = await shell.send_command("dir"); console.log(out.toString()); ``` -------------------------------- ### Example of _make_bitwise_enum usage Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/internal.md Example call to `_make_bitwise_enum` with `all_prop` and `none_prop`, producing a bitmask enum. The comment shows the resulting mapping. ```js const flags = _make_bitwise_enum(["read", "write"], { all_prop: "all", none_prop: "none" }); // { read: 1, write: 2, all: 3, none: 0 } ``` -------------------------------- ### device_toast usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-invites-messaging.md Shows how to call device_toast to send a toast notification to a node. ```javascript const resp = await session.device_toast(["node//abc"], "Backup complete"); ``` -------------------------------- ### Session.create() usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session.md Shows basic creation with a WebSocket URL and credentials, plus error handling for an unavailable server. The promise rejects with the socket error code (e.g., 'ECONNREFUSED'). ```javascript import { Session } from "libmeshctrl"; // Basic const session = await Session.create("wss://mesh.example.com", { user: "admin", password: "s3cret" }); // Error handling: an unavailable server rejects the promise try { await Session.create("ws://localhost:1", { user: "a", password: "b" }); } catch (err) { console.log(err); // e.g. "ECONNREFUSED" (rejected with the socket error code) } ``` -------------------------------- ### run_command method signature and usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-devices.md Declares the async run_command method that runs a command on specified nodes with options for PowerShell and user context. The usage example shows running 'ipconfig' with PowerShell and handling errors with a try/catch block. ```javascript async run_command(nodeids, command, {powershell=false, runasuser=false, runasuseronly=false}={}, timeout=null) ``` ```javascript const out = await session.run_command(["node//abc"], "ipconfig", { powershell: true }, 30000); for (const [nodeid, text] of Object.entries(out)) console.log(nodeid, text); // Error handling try { await session.run_command(["node//abc"], "exit 1", {}, 5000); } catch (e) { console.log(e.message); } ``` -------------------------------- ### generate_invite_link usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-invites-messaging.md Generates an invite link with a 24-hour expiry and remote control rights. Logs the invite link to the console. ```javascript const { inviteLink } = await session.generate_invite_link("production", 24, { flags: MESHRIGHTS.remotecontrol }); console.log(inviteLink); ``` -------------------------------- ### add_login_token usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-users.md Creates a login token named "ci-token" with a 60-minute expiration. The returned promise resolves to the server response object. ```javascript const token = await session.add_login_token("ci-token", 60); ``` -------------------------------- ### interuser usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session.md Example of sending a fire-and-forget inter-user message to all sessions of user 'admin' with payload { ping: 1 }. ```js session.interuser({ ping: 1 }, { user: "admin" }); ``` -------------------------------- ### _Shell constructor(session, node_id) Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shells.md Starts tunnel initialization for a terminal shell. Use _Shell.create to await the handshake. ```APIDOC ## constructor(session, node_id) ### Description Starts tunnel initialization for a terminal shell on the specified node. Use `_Shell.create(session, node_id)` to await the handshake. ### Method constructor ### Parameters - **session** (Session) - Required - The logged-in session. - **node_id** (string) - Required - Node to open the shell on. ### Returns `_Shell` instance (initialization asynchronous). ``` -------------------------------- ### session.list_user_groups([timeout]) Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Gets user groups. Admin will get all user groups, otherwise get limited user groups. Returns a promise that resolves to an array of group objects or null if no groups are found. ```APIDOC ## session.list_user_groups([timeout]) ### Description Get user groups. Admin will get all user groups, otherwise get limited user groups ### Method session.list_user_groups ### Parameters #### Query Parameters - **timeout** (number) - Optional - duration in milliseconds to wait for a response before throwing an error ### Returns Promise.<(Array.<Object>|null)> - List of groups, or null if no groups are found ### Throws - SocketError - Info about socket closure - TimeoutError - Command timed out ``` -------------------------------- ### Session upload method signature and usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-files.md Asynchronous method to upload a stream to a remote destination. Returns Promise resolving to {result, size}, where result is "success" or "error" per _Files#upload internals. Example uses a read stream from a local file. ```javascript async upload(nodeid, source, target, unique_file_tunnel=false) ``` ```javascript const res = await session.upload("node//abc", fs.createReadStream("./fw.bin"), "C:\\fw.bin"); console.log(res.result, res.size); ``` -------------------------------- ### session.list_devices([options], [timeout]) Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Get devices to which the user has access. ```APIDOC ## session.list_devices([options], [timeout]) ### Description Get devices to which the user has access. ### Method session.list_devices ### Endpoint session.list_devices([options], [timeout]) ### Parameters #### Path Parameters - **options** (Object) - Optional - Default: {} - **options.details** (boolean) - Optional - Get device details. Default: false - **options.group** (string) - Optional - Get devices from specific group by name. Overrides meshid. Default: null - **options.meshid** (string) - Optional - Get devices from specific group by id. Default: null - **timeout** (number) - Optional - duration in milliseconds to wait for a response before throwing an error ### Response #### Success Response - **Promise.<Array.<Object>>** - List of nodes #### Error Handling - **SocketError** - Info about socket closure - **TimeoutError** - Command timed out ``` -------------------------------- ### _Shell constructor signature Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shells.md Constructor for _Shell. Starts tunnel initialization; use _Shell.create(session, node_id) to await the handshake. ```javascript constructor(session, node_id) ``` -------------------------------- ### broadcast usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-invites-messaging.md Shows how to call broadcast to send a message to all users or to a specific user by userid. ```javascript await session.broadcast("Maintenance in 10 minutes"); await session.broadcast("Hi Jane", "user//admin//jdoe"); ``` -------------------------------- ### Session file_explorer method signature and usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-files.md Asynchronous method to open a file explorer tunnel for a node. Parameter unique controls whether to reuse the cached _Files or create a fresh one. Returns a Promise of a _Files object. Example shows opening and closing the explorer. ```javascript async file_explorer(nodeid, unique=false) ``` ```javascript const files = await session.file_explorer("node//abc"); const dir = await files.ls("C:\\"); // close it when done files.close(); ``` -------------------------------- ### device_info usage and error handling Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-devices.md Example usage of device_info. Fetches info for a node and logs its name and lastconnect. Includes error handling for a non-existent node, checking the error type against ERRORS.ValueError.type. ```javascript const info = await session.device_info("node//abc"); console.log(info.node.name, info.node.lastconnect); // Error handling try { await session.device_info("node//does-not-exist"); } catch (e) { if (e.type === ERRORS.ValueError.type) { /* not found */ } } ``` -------------------------------- ### send_invite_email usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-invites-messaging.md Sends an invite email to a recipient with a custom name and message. Returns a Promise resolving to true on success. ```javascript const ok = await session.send_invite_email("production", "tech@example.com", { name: "Tech", message: "Join our mesh!" }); ``` -------------------------------- ### Calling run_console_command with node array Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-devices.md Example of calling run_console_command on a session object with an array of node IDs. Passes the command 'help' and demonstrates the required signature. ```javascript const out = await session.run_console_command(["node//abc"], "help"); ``` -------------------------------- ### Session download method signature and usage examples with error handling Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-files.md Asynchronous method to download a remote file to a writable stream. If target is null, creates a PassThrough stream. Throws Error with message like "error: 0 bytes downloaded" on failure. Two examples show stream-out style and error handling. ```javascript async download(nodeid, source, target=null, unique_file_tunnel=false) ``` ```javascript // Stream-out style const stream = await session.download("node//abc", "/etc/hostname"); stream.pipe(process.stdout); // Error handling try { await session.download("node//abc", "C:\\missing.txt", fs.createWriteStream("./out.bin")); } catch (e) { console.log(e.message); // "error: 0 bytes downloaded" } ``` -------------------------------- ### Use _Deferred Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/internal.md Example usage of _Deferred: create a deferred, attach a then handler, resolve with a value, and observe the resolved property becomes true. ```javascript const d = new _Deferred(); d.then((v) => console.log("resolved:", v)); d.resolve(42); // later: d.resolved === true ``` -------------------------------- ### add_device_group usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-groups.md Creates a device group named "production" with hostname sync and record sessions features, plus desktop and terminal notify consent flags. Uses MESHFEATURES and CONSENTFLAGS bitmask constants. ```javascript const mesh = await session.add_device_group("production", { features: MESHFEATURES.hostnamesync | MESHFEATURES.recordsessions, consent: CONSENTFLAGS.desktopnotify | CONSENTFLAGS.terminalnotify }); ``` -------------------------------- ### session.list_user_sessions([timeout]) Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Gets a list of connected users. Admin only. Returns a promise that resolves to an array of user session objects. ```APIDOC ## session.list_user_sessions([timeout]) ### Description Get list of connected users. Admin Only. ### Method session.list_user_sessions ### Parameters #### Query Parameters - **timeout** (number) - Optional - duration in milliseconds to wait for a response before throwing an error ### Returns Promise.<Array.<Object>> - List of user sessions ### Throws - SocketError - Info about socket closure - TimeoutError - Command timed out ``` -------------------------------- ### Session download_file method signature and usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-files.md Asynchronous method to download a remote file to a local file path. Local file is opened with fs.createWriteStream. Returns Promise resolving to the write stream once finished, with failure mode as in download. ```javascript async download_file(nodeid, source, filepath, unique_file_tunnel=false) ``` ```javascript await session.download_file("node//abc", "/var/log/syslog", "./syslog"); ``` -------------------------------- ### download method signature Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-files.md Downloads a remote file to a writable stream. Sends a start action and writes binary frames to the target. Returns a promise with success/canceled and byte size. ```javascript async download(source, target) ``` -------------------------------- ### Basic Session connection and error handling Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session.md Creates a Session with password authentication and awaits initialization. Also demonstrates synchronous errors for invalid URL and missing credentials. ```javascript // Basic: anonymous-credential-free password connect const session = new Session("wss://mesh.example.com", { user: "admin", password: "s3cret" }); await session.initialized; // Error handling: invalid URL and missing credentials are synchronous throws try { const bad = new Session("https://not-a-websocket.url", { user: "admin" }); // no password } catch (e) { console.log(e.message); // "No login credentials given" } ``` -------------------------------- ### Remove device share example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shares.md Example of removing a device share using a share object's publicid. ```javascript await session.remove_device_share("node//abc", share.publicid); ``` -------------------------------- ### _Files.mkdir(directory) ⇒ Promise.<boolean> Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Creates a directory on the device. ```APIDOC ## _Files.mkdir(directory) ⇒ Promise.<boolean> ### Description Return a directory listing from the device. (Note: The description in the source says 'Return a directory listing' but the method name and return type indicate directory creation. The source text is ambiguous; this is the documented description.) ### Method Instance method ### Parameters - **directory** (string) - Required - Path to the directory you wish to list ### Returns - **Promise.<boolean>** - True if directory creation succeeded ### Throws - **SocketError** - Info about socket closure ``` -------------------------------- ### stop_listening_to_events usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session.md Example of storing the stop function returned by listen_to_events and later calling stop_listening_to_events to unregister the listener. ```js const stop = session.listen_to_events(handler); // ...later: session.stop_listening_to_events(stop); ``` -------------------------------- ### Initialize Session with Session.create Source: https://github.com/ylianst/libmeshctrl/blob/main/readme.md Preferred way to initialize a Session asynchronously using the static create function. Must be awaited before interacting with the server. ```javascript import { Session } from "LibMeshCtrl" let session = await Session.create(url, {options}) session.list_users() ... ``` -------------------------------- ### add_device_share(nodeid, name, {type=SHARINGTYPE.desktop, consent=null, start=null, end=null, duration=60*60}={}, timeout=null) Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shares.md Creates a new device share for a guest user. Sends a 'createDeviceShareLink' action with share details and returns the new share payload. ```APIDOC ## add_device_share(nodeid, name, {type=SHARINGTYPE.desktop, consent=null, start=null, end=null, duration=60*60}={}, timeout=null) ### Description Creates a new device share for a guest user. Sends a `createDeviceShareLink` action with share details and returns the new share payload. ### Method SDK method (async) ### Parameters - **nodeid** (string) - Required - Node to share. - **name** (string) - Required - Guest name. - **options.type** (SHARINGTYPE) - Optional - Share type; mapped to the server's numeric protocol via `SHARINGTYPENUM` (`desktop` → 1, `terminal` → 2). - **options.consent** (CONSENTFLAGS bitmask) - Optional - Consent flags; `null` defaults to `CONSENTFLAGS.desktopnotify` for desktop shares and `CONSENTFLAGS.terminalnotify` for terminal shares. - **options.start** (number|Date) - Optional - Start time (ms epoch); `null` → now. - **options.end** (number|Date) - Optional - End time; `null` → `start + duration`. - **options.duration** (number) - Optional - Duration in seconds used when `end` is `null`. - **timeout** (number) - Optional - See page intro. ### Request Example ```js const share = await session.add_device_share("node//abc", "consultant", { type: SHARINGTYPE.terminal, start: Date.now(), duration: 2 * 60 * 60 }); // Error handling try { await session.add_device_share("node//abc", "x", { start: Date.now() + 60000, duration: 30 }); } catch (e) { console.log(e.message); // "End time must be ahead of start time" } ``` ### Response Returns `Promise<Object>` — the new share payload with `action`, `nodeid`, `tag`, `responseid` removed. ### Errors - `Error("End time must be ahead of start time")` when `end <= start` (after defaults are applied) - `ServerError` on non-`"ok"` - `SocketError` / `TimeoutError` as usual ``` -------------------------------- ### Edit device group with invite codes example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-groups.md Example usage of edit_device_group to update a group's name and set an invite code with interactive-only flag. The method returns a Promise that resolves to true on success or a ServerError on failure. ```javascript await session.edit_device_group("mesh//abc", { name: "production-v2", invite_codes: ["WORK-2024"], interactiveonly: true }); ``` -------------------------------- ### _Files.ls(directory) ⇒ Promise.<Array.<Object>> Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Returns a directory listing from the device. ```APIDOC ## _Files.ls(directory) ⇒ Promise.<Array.<Object>> ### Description Return a directory listing from the device. ### Method Instance method ### Parameters - **directory** (string) - Required - Path to the directory you wish to list ### Returns - **Promise.<Array.<Object>>** - An array of objects representing the directory listing ### Throws - **SocketError** - Info about socket closure ``` -------------------------------- ### Initialize Session with new and await initialized Source: https://github.com/ylianst/libmeshctrl/blob/main/readme.md Alternative initialization by instantiating the Session object directly and awaiting the initialized property. ```javascript let session = new Session(url, {options}) await session.initialized ``` -------------------------------- ### new Session(url, options) Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session.md Creates a new Session instance that connects to a MeshCentral server via WebSocket. The constructor validates the URL and credentials, and begins the connection initialization process. ```APIDOC ## new Session(url, options) ### Description Creates a new Session instance representing an authenticated WebSocket connection to a MeshCentral server. The constructor validates the URL and credentials, and starts the connection initialization process. Await the `initialized` property before issuing commands. ### Method Constructor ### Endpoint `new Session(url, options)` ### Parameters #### Constructor Parameters - **url** (string) - Required - URL of the MeshCentral server; must start with `"ws://"` or `"wss://"`. A trailing `/control.ashx` is appended automatically. - **options.user** (string) - Optional - Username to connect with. Can also be a username generated from a token. - **options.domain** (string) - Optional - Domain on the server to connect to. - **options.password** (string) - Optional - Password to connect with. Can also be a password generated from a token. - **options.loginkey** (string) - Optional - Path to a key file from already-handled login; overrides username/password. - **options.proxy** (string) - Optional - `"url:port"` of a proxy server. - **options.token** (string) - Optional - Login token (appended to the auth header as base64). - **options.ignoreSSL** (boolean) - Optional - Ignore SSL errors on the WebSocket. ### Request Example ```js const session = new Session("wss://mesh.example.com", { user: "admin", password: "s3cret" }); await session.initialized; ``` ### Response #### Success Response Returns an uninitialized `Session` instance. The connection initialization starts immediately; await `session.initialized` to know when the session is ready. #### Error Handling - **Invalid URL** - Thrown if `url.length < 5` or the url does not start with `"ws://"` or `"wss://"`. - **No login credentials given** - Thrown if `user == null` or both `password == null` and `loginkey == null`. - **Invalid login key** - Thrown if a `loginkey` file was read but is not exactly 160 characters (hex). - **I/O errors** - Thrown from reading the login key file (except `ENOENT`, which is swallowed). ``` -------------------------------- ### power_off_devices method signature and usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-devices.md Declares the async power_off_devices method that sends a power action with actiontype 2 to power off the specified nodes. Returns the raw server response as Promise<boolean> without a result check. The usage example shows calling wake_devices and power_off_devices with node IDs. ```javascript async power_off_devices(nodeids, timeout=null) ``` ```javascript await session.wake_devices(["node//abc", "node//def"]); await session.power_off_devices("node//abc"); ``` -------------------------------- ### Import internal helpers Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/internal.md Demonstrates importing and destructuring internal helpers from the library. ```javascript import { _Internal } from "libmeshctrl"; const { _Deferred, _Tunnel, _SizeChunker, _compare_obj, _make_enum, _make_bitwise_enum } = _Internal; ``` -------------------------------- ### _Shell.create(session, node_id) Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shells.md Static async factory method that creates and initializes a _Shell instance, awaiting the handshake completion. ```APIDOC ## _Shell.create(session, node_id) ### Description Static async factory method that creates a `_Shell` instance and waits for the tunnel handshake to complete. On completion, sets `alive = true` and resolves the `initialized` promise. ### Method async static ### Parameters - **session** (Session) - Required - The logged-in session. - **node_id** (string) - Required - Node to open the shell on. ### Returns `Promise<_Shell>` - Initialized shell tunnel. ``` -------------------------------- ### Using smart_shell to run a command Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shells.md Creates a smart shell on node "node//abc" that waits for the prompt regex /\$ /, sends the command "ls -la", and prints the output. ```javascript const sh = await session.smart_shell("node//abc", /\$ /); const out = await sh.send_command("ls -la"); console.log(out.toString()); ``` -------------------------------- ### remove_user_group usage example Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-groups.md Removes the user group with id 'ugrp//engineering'. The group id is prefixed with 'ugrp//' as documented. ```javascript await session.remove_user_group("ugrp//engineering"); ``` -------------------------------- ### Session.create(url, [options]) Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Static method to create a new Session instance. ```APIDOC ## Session.create(url, [options]) ### Description Create a new Session. ### Method Static method ### Parameters - **url** (string) - Required - URL of meshcentral server. - **[options]** (Object) - Optional - Same as constructor options. ### Returns - **Session** - A new Session instance. ``` -------------------------------- ### Using server_info() to log domain and serverTime Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session.md Calls session.server_info() and logs the domain and serverTime properties from the returned object. ```javascript const info = await session.server_info(); console.log(info.domain, info.serverTime); ``` -------------------------------- ### add_device_share method signature Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shares.md Method signature for adding a device share with options for type, consent, start, end, and duration. ```javascript async add_device_share(nodeid, name, {type=SHARINGTYPE.desktop, consent=null, start=null, end=null, duration=60*60}={}, timeout=null) ``` -------------------------------- ### session.add_user(name, password, [options], [timeout]) Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Adds a new user with the given credentials and options. ```APIDOC ## session.add_user(name, password, [options], [timeout]) ### Description Add a new user ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - username - **password** (string) - Required - user's starting password - **[options]** (Object) - Optional - - **[options.randompass]** (boolean) - Optional - Generate a random password for the user. Overrides password - **[options.domain]** (string) - Optional - Domain to which to add the user - **[options.email]** (string) - Optional - User's email address - **[options.emailverified]** (boolean) - Optional - Pre-verify the user's email address - **[options.resetpass]** (boolean) - Optional - Force the user to reset their password on first login - **[options.realname]** (string) - Optional - User's real name - **[options.phone]** (string) - Optional - User's phone number - **[options.rights]** (USERRIGHTS) - Optional - Bitwise mask of user's rights on the server - **[timeout]** (number) - Optional - duration in milliseconds to wait for a response before throwing an error ### Request Example N/A ### Response #### Success Response (200) - **result** (Boolean) - true on success #### Response Example N/A ### Errors - **ServerError** - Error text from server if there is a failure - **SocketError** - Info about socket closure - **TimeoutError** - Command timed out ``` -------------------------------- ### new _Files(session, node_id) Source: https://github.com/ylianst/libmeshctrl/blob/main/doc/api.md Constructor for _Files. Initializes a new instance with a session and node ID. ```APIDOC ## new _Files(session, node_id) ### Description Constructor for _Files. Initializes a new instance of the _Files class. ### Method Constructor ### Parameters - **session** (Session) - Required - Session representing a logged in user - **node_id** (string) - Required - Node on which to open the file explorer ### Returns - **_Files** - Instance of _Files ``` -------------------------------- ### Set x-meshauth header in _initialize() Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/endpoints.md Builds the authentication header as base64(user),base64(password)[,base64(token)] when a password is set. The token is optional and appended only if present. ```javascript options.headers = { 'x-meshauth': Buffer.from('' + this._user).toString('base64') + ',' + Buffer.from('' + this._password).toString('base64') + token } ``` -------------------------------- ### Internal initialization method Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/internal.md Internal negotiation sequence for setting up the tunnel. Not meant for direct calls. ```javascript _initialize() ``` -------------------------------- ### list_device_shares method signature Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-shares.md Method signature for listing device shares. Sends a non-namespaced command and returns a promise of an array of share objects. ```javascript async list_device_shares(nodeid, timeout=null) ``` -------------------------------- ### device_open_url(nodeid, url, timeout=null) Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/api-reference/session-invites-messaging.md Opens a URL in the device's browser. Sends an event and waits for a matching server event, returning a promise that resolves to true on success or rejects with an error. ```APIDOC ## device_open_url(nodeid, url, timeout=null) ### Description Opens a URL in the device's browser. Sends an event and waits for a matching server event, returning a promise that resolves to true on success or rejects with an error. ### Method N/A (Event-driven) ### Endpoint N/A (Event-driven) ### Parameters #### Parameters - **nodeid** (string) - Required - Target node. - **url** (string) - Required - URL to open in the device's browser. - **timeout** (number) - Optional - Only arms the timeout rejection when truthy. ### Request Example ```js const ok = await session.device_open_url("node//abc", "https://meshcentral.com"); ``` ### Response #### Success Response - **Promise<boolean>** - Resolves to `true` if the event reports `data.success`. #### Error Handling - Rejects with `Error("Failed to open url")` if the event has no success flag. - Rejects with `ServerError(data.result)` if the command reply is not `"ok"`. - Rejects with `TimeoutError` when a truthy `timeout` elapses. #### Response Example ```js try { await session.device_open_url("node//abc", "about:blank", 10000); } catch (e) { console.log(e.message); } // "Failed to open url" or a ServerError ``` ``` -------------------------------- ### Define SHARINGTYPENUM enum Source: https://github.com/ylianst/libmeshctrl/blob/main/_autodocs/types.md Creates the SHARINGTYPENUM enum mapping SHARINGTYPE to numeric values starting at 0x1. Used internally in Session#add_device_share as p: SHARINGTYPENUM[type]. ```javascript const SHARINGTYPENUM = _make_enum(["desktop", "terminal"], {start_value: 0x1}) ```