UNPKG

dbus-sdk

Version:

A Node.js SDK for interacting with DBus, enabling seamless service calling and exposure with TypeScript support

268 lines 14.9 kB
import { CreateConnectOpts } from '../types/CreateConnectOpts'; import { Duplex } from 'node:stream'; import { ConnectOpts } from '../types/ConnectOpts'; import { BinaryLike } from 'node:crypto'; import { HandshakeOpts } from '../types/HandshakeOpts'; import EventEmitter from 'node:events'; import { NetConnectOpts } from 'net'; import { DBusMessage } from './DBusMessage'; /** * A class representing a low-level DBus connection. * Handles the creation of streams (TCP, Unix socket, etc.), authentication handshake, * and message reading/writing over the connection. Extends EventEmitter to emit events * for messages, connection closure, and errors. */ export declare class DBusConnection extends EventEmitter { #private; /** * Default authentication methods supported by this connection class. * Used in the handshake process in order of preference. */ protected static defaultAuthMethods: string[]; /** * Default timeout for connection attempts in milliseconds. * Used if no specific timeout is provided in connection options. */ protected static defaultConnectTimeout: number; /** * Computes the SHA-1 hash of the input data. * Used during DBUS_COOKIE_SHA1 authentication to generate a response based on challenges and cookie. * * @param input - The data to hash, typically a string or buffer. * @returns The hexadecimal representation of the SHA-1 hash. */ protected static sha1(input: BinaryLike): string; /** * Retrieves the user's home directory path based on the platform. * Used to locate DBus keyring files for authentication, adapting to Windows or Unix-like systems. * * @returns The path to the user's home directory as a string. */ protected static getUserHome(): string; /** * Retrieves a DBus authentication cookie from the user's keyring file. * Used during DBUS_COOKIE_SHA1 authentication to fetch a secret cookie for the response. * * @param context - The context name for the cookie (defaults to 'org_freedesktop_general' if empty). * @param id - The ID of the cookie to retrieve from the keyring file. * @returns A Promise resolving to the cookie value as a string. * @throws {UserPermissionError} If the keyring directory has incorrect permissions or the cookie is not found. */ protected static getCookie(context: string, id: string): Promise<string>; /** * Performs the DBus connection handshake with the server over the provided stream. * Attempts authentication using the specified or default methods in sequence until one succeeds. * * @param stream - The duplex stream for communication with the DBus server. * @param opts - Optional handshake options, including custom authentication methods and UID. * @returns A Promise resolving to a tuple of [authMethod, uid, guid] upon successful handshake. * @throws {AuthError} If no authentication method succeeds or if all attempts fail. */ protected static handshake(stream: Duplex, opts?: HandshakeOpts): Promise<[string, string, string]>; /** * Attempts authentication using a specific method. * Reads server responses and handles the authentication protocol for the chosen method. * Supports 'EXTERNAL', 'DBUS_COOKIE_SHA1', and 'ANONYMOUS' authentication mechanisms. * * @param stream - The duplex stream for communication with the DBus server. * @param authMethod - The authentication method to try (e.g., 'EXTERNAL', 'DBUS_COOKIE_SHA1', 'ANONYMOUS'). * @param id - The hexadecimal representation of the user ID used for authentication. * @returns A Promise resolving to the server GUID upon successful authentication. * @throws {AuthError} If authentication fails or the method is unsupported. */ protected static tryAuth(stream: Duplex, authMethod: string, id: string): Promise<string>; /** * Creates a duplex stream for DBus communication based on network connection options. * Handles connection setup, timeouts, and errors for TCP or Unix socket connections. * * @param opts - Network connection options, including host, port, path, and timeout settings. * @returns A Promise resolving to a Duplex stream for communication with the DBus server. * @throws {TimeoutError} If the connection attempt times out after the specified duration. * @throws {Error} If the connection fails due to other reasons (e.g., network issues). */ protected static createDuplexStream(opts: NetConnectOpts): Promise<Duplex>; /** * Creates a TCP stream for DBus communication. * Converts port input to a number and sets a default host if not provided. * * @param timeout - The connection timeout duration in milliseconds. * @param port - The port number (or string representation) to connect to. * @param host - Optional host address to connect to (defaults to 'localhost' if not specified). * @returns A Promise resolving to a Duplex stream for TCP communication with the DBus server. */ protected static createTCPStream(timeout: number, port: number | string, host?: string): Promise<Duplex>; /** * Creates a Unix socket stream for DBus communication. * Uses the provided socket path for local communication. * * @param timeout - The connection timeout duration in milliseconds. * @param addr - The file path to the Unix socket for communication. * @returns A Promise resolving to a Duplex stream for Unix socket communication with the DBus server. */ protected static createUnixStream(timeout: number, addr: string): Promise<Duplex>; /** * Creates a stream for DBus communication based on the provided options or environment variables. * Supports custom streams, direct socket paths, TCP connections, or bus addresses from environment. * Iterates through semicolon-separated bus addresses if multiple are provided, attempting each in sequence. * * @param opts - Optional connection options specifying a stream, socket path, TCP details, or bus address. * @returns A Promise resolving to a Duplex stream for communication with the DBus server. * @throws {UnknownBusAddressError} If no bus address is provided or found in environment variables. * @throws {UnknownBusTypeError} If the bus address type is unsupported (not 'tcp' or 'unix'). * @throws {NotEnoughParamsError} If required parameters are missing for a specific bus type. * @throws {CreateStreamFailedError} If stream creation fails for all attempted addresses. */ protected static createStream(opts?: ConnectOpts): Promise<Duplex>; /** * Static method to create a DBus connection. * Establishes a stream based on provided or default options, performs the handshake to authenticate, * and returns a fully initialized DBusConnection instance. * * @param opts - Optional connection and handshake options, including stream, bus address, or auth methods. * @returns A Promise resolving to a DBusConnection instance ready for communication. */ static createConnection(opts?: CreateConnectOpts): Promise<DBusConnection>; /** * Getter for the authentication method used in this connection. * * @returns The authentication method (e.g., 'EXTERNAL', 'DBUS_COOKIE_SHA1', 'ANONYMOUS') as a string. */ get authMethod(): string; /** * Getter for the user ID used during authentication. * * @returns The user ID as a number. */ get uid(): number; /** * Getter for the server-provided GUID. * * @returns The GUID as a string, identifying this connection on the server. */ get guid(): string; /** * Checks if the connection is currently active. * Determines the connection status by checking if the stream is not closed. * * @returns True if the stream is not closed (connection is active), false otherwise. */ get connected(): boolean; /** * Constructor for DBusConnection. * Initializes the connection with the provided stream and authentication details, * sets up event listeners for reading messages, and handles connection closure and errors. * Implements a state machine to parse incoming DBus messages by reading headers and bodies. * * @param stream - The duplex stream for communication with the DBus server. * @param authMethod - The authentication method that succeeded during handshake. * @param uid - The user ID used during authentication, as a string (later parsed to number). * @param guid - The GUID provided by the server after successful authentication. * @param advancedResponse - Boolean flag to enable advanced response handling, where DBus return messages are organized using DBusTypeClass instances. * @param convertBigIntToNumber - Boolean flag to enable auto convert bigint to javascript number. */ constructor(stream: Duplex, authMethod: string, uid: string, guid: string, advancedResponse?: boolean, convertBigIntToNumber?: boolean); /** * Writes data to the DBus connection stream. * Used to send encoded DBus messages to the server. * * @param data - The Buffer containing the data to write to the stream. * @returns True if the write operation was successful, false otherwise (e.g., if the stream is not writable). */ write(data: Buffer): boolean; /** * Closes the DBus connection stream. * Ends the connection, optionally executing a callback when the stream is fully closed. * * @param callback - Optional callback function to execute when the stream is closed. * @returns This instance for method chaining. */ end(callback?: () => void): this; /** * Adds an event listener for DBus connection events. * Supports multiple event types with specific callback signatures for handling messages, * connection closure, and errors. This method allows for type-safe event handling based on * the event name provided. * * @param eventName - The name of the event to listen for. Specific event names have predefined * callback signatures for type safety. * @param listener - The callback function to execute when the event occurs. The signature of the * callback depends on the event name. * @returns This instance for method chaining. * * @example * connection.on('message', (message) => console.log('Received message:', message)); * connection.on('close', () => console.log('Connection closed')); * connection.on('error', (error) => console.error('Connection error:', error)); */ on(eventName: 'message', listener: (message: DBusMessage) => void): this; /** * Adds an event listener for the 'close' event, which is emitted when the DBus connection is closed. * * @param eventName - The string 'close', indicating the connection closure event. * @param listener - A callback function with no arguments, invoked when the connection closes. * @returns This instance for method chaining. */ on(eventName: 'close', listener: () => void): this; /** * Adds an event listener for the 'error' event, which is emitted when an error occurs on the DBus connection. * * @param eventName - The string 'error', indicating the connection error event. * @param listener - A callback function that receives an Error object as its argument, invoked when an error occurs. * @returns This instance for method chaining. */ on(eventName: 'error', listener: (error: Error) => void): this; /** * Adds an event listener for a generic or custom event name as a string. * This overload allows for flexibility with event names not predefined in the class. * * @param eventName - A string representing any custom or non-predefined event name. * @param listener - A callback function accepting variable arguments, used for handling custom events. * @returns This instance for method chaining. */ on(eventName: string, listener: (...args: any[]) => void): this; /** * Adds a one-time event listener for DBus connection events. * The listener is executed only once when the specified event occurs and is then removed. * Supports multiple event types with specific callback signatures for handling messages, * connection closure, and errors. This method allows for type-safe event handling based on * the event name provided. * * @param eventName - The name of the event to listen for. Specific event names have predefined * callback signatures for type safety. * @param listener - The callback function to execute once when the event occurs. The signature of * the callback depends on the event name. * @returns This instance for method chaining. * * @example * connection.once('message', (message) => console.log('First message:', message)); * connection.once('close', () => console.log('Connection closed')); * connection.once('error', (error) => console.error('First error:', error)); */ once(eventName: 'message', listener: (message: DBusMessage) => void): this; /** * Adds a one-time event listener for the 'close' event, which is emitted when the DBus connection is closed. * * @param eventName - The string 'close', indicating the connection closure event. * @param listener - A callback function with no arguments, invoked once when the connection closes. * @returns This instance for method chaining. */ once(eventName: 'close', listener: () => void): this; /** * Adds a one-time event listener for the 'error' event, which is emitted when an error occurs on the DBus connection. * * @param eventName - The string 'error', indicating the connection error event. * @param listener - A callback function that receives an Error object as its argument, invoked once when an error occurs. * @returns This instance for method chaining. */ once(eventName: 'error', listener: (error: Error) => void): this; /** * Adds a one-time event listener for a generic or custom event name as a string. * This overload allows for flexibility with event names not predefined in the class. * * @param eventName - A string representing any custom or non-predefined event name. * @param listener - A callback function accepting variable arguments, used for handling custom events once. * @returns This instance for method chaining. */ once(eventName: string, listener: (...args: any[]) => void): this; } //# sourceMappingURL=DBusConnection.d.ts.map