Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .jshintrc
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@
"before": true,
"afterEach": true,
"beforeEach": true,
"after": true
"after": true,
// should.js (assertion library) exposes `should` as a global
"should": true
}
}
42 changes: 42 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,48 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.0.0] - 2026-07-16

### Added
- Non-root import path: `require('linux-user/non-root')` exposes only the
read-only functions that do not require root and emits no root warning.
Also available as `require('linux-user').nonRoot`.
- Read-only promise set via `.promise.nonRoot()` and the non-root module's
`.promise()` factory.
- Optional timeout support for spawned commands (`opts.timeout`) to prevent
hung child processes from blocking the library.

### Changed
- `spawnWrapper` now follows the Node.js `(err, result)` contract: errors are
`Error` objects (or `null` on success), and a non-zero exit code is treated as
a failure. Callbacks are now invoked at most once.
- `getExpiration` parses `chage --list` output under the `C` locale and is no
longer order/index dependent, so it is robust against localized output.
- `addSSHtoUser` now uses `spawn` with argument arrays instead of a shell
`exec` string, eliminating shell-injection risk from the home directory path.
- Tests now skip root-dependent cases automatically when not running as root.

### Fixed
- `addUser` no longer calls its callback twice or swallows the `useradd` error.
- `addGroup` now propagates the `groupadd` error instead of always fetching the
group info.
- `addSSHtoUser` no longer crashes with `Cannot read properties of null` when
the user does not exist; it returns an `Error`.
- `getExpiration` returns the error instead of throwing when `chage` fails.
- `setPassword` now reports a failure when `passwd` exits non-zero instead of
calling back with no error.
- `removeUser` and `addUserToGroup` now pass `Error|null` instead of the raw
numeric exit code as the callback's first argument.
- `promise()` no longer hangs on `validateUsername`; it is passed through as a
synchronous function.
- `build_user_command` no longer injects `null` arguments when a flag map
returns `undefined`.
- `getUsers`/`getGroups` no longer drop the last record when `/etc/passwd` or
`/etc/group` has no trailing newline.
- TypeScript: `selinux_user` is now typed as `string` (it is passed to
`--selinux-user <value>`), and `other_args` accepts `string | string[]`.
- Removed dead commented-out code from `setPassword`.

## [1.2.0] - 2024-01-09

### Added
Expand Down
53 changes: 48 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,52 @@ current user will also work with out root.

The testing libraries only work with NodeJS 6 and up.

UPDATE!

Newer version of NPM does not allows executing as root, if you run into this
issue, call mocha directly:
Tests that modify system state require root. When the suite is **not** run as
root, those tests are automatically skipped and the read-only tests still run,
so `npm test` passes in CI and on dev machines without root. To exercise the
full suite, run as root:

```bash
./node_modules/mocha/bin/mocha
sudo ./node_modules/mocha/bin/mocha
```

Newer version of NPM does not allow executing as root, if you run into this
issue, call mocha directly as shown above.

## Non-root usage

Most functions that modify the system require root, but the read-only
functions only read `/etc/passwd` and `/etc/group` (world-readable) or operate
on the calling user, so they work without root.

Importing the main module prints a warning when it is not running as root. If
you only need the read-only functions you can import the non-root path, which
exposes only those functions and emits **no** root warning:

```js
// read-only subset, no root warning, safe to use without root
var linuxUser = require('linux-user/non-root');

linuxUser.getUsers(function (err, users) {
// ...
});
```

The non-root export exposes: `getUsers`, `getGroups`, `getUserInfo`,
`getUserGroups`, `getExpiration`, `validateUsername`, and `verifySSHKey`, plus
a read-only `promise()` factory. The same set is also available as
`require('linux-user').nonRoot` for convenience (the main import still emits the
root warning in that case).

## Usage

This works with your normal require and execute callback functions. Every method
takes a callback and is non-blocking.

All callbacks follow the Node.js convention `(err, result)`. Errors are always
`Error` objects (or `null` on success) -- they are never passed as strings or
booleans.

### Examples

* add Linux user
Expand Down Expand Up @@ -123,6 +155,17 @@ version of NodeJS( less then 8 ) you will need something like it.

This will work with `.then()`, `.catch()` and the `async`/`await` pattern.

Synchronous helpers such as `validateUsername` are **not** promisified -- they
are passed through unchanged and still return their value directly (promisifying
them would produce a promise that never settles). The read-only functions are
available as a promise set too:

```js
var p = require('linux-user/non-root').promise();
var users = await p.getUsers();
var valid = p.validateUsername('bob'); // still synchronous, returns boolean
```

```js

let user = await addUser({username:"gkuchan", create_home:true, shell:null});
Expand Down
87 changes: 72 additions & 15 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ export interface UserCreationArgs {
expiredate?: string | Date;
skel?: string;
system?: boolean;
selinux_user?: boolean;
other_args?: string;
selinux_user?: string;
other_args?: string | string[];
}

export interface UserInfo {
Expand All @@ -30,7 +30,7 @@ export interface GroupInfo {
}

export interface UserExpirationInfo {
changed: Date;
changed: Date | null;
passwordExpires: null | Date;
inactive: null | Date;
accountExpires: null | Date;
Expand All @@ -53,20 +53,15 @@ export default class LinuxUser {
args: UserCreationArgs | string,
callback: (error: ErrorType, user?: UserInfo | null) => void
): void;
static removeUser(
username: string,
callback: (error: ErrorType) => void
): void;
static removeUser(username: string, callback: (error: ErrorType) => void): void;
static getUserGroups(
username: string,
callback: (error: ErrorType, groups?: string[]) => void
): void;
static getUsers(
callback: (error: ErrorType, users?: UserInfo[]) => void
): void;
static getUsers(callback: (error: ErrorType, users?: UserInfo[]) => void): void;
static getUserInfo(
username: string,
callback: (error: ErrorType, user?: UserInfo) => void
callback: (error: ErrorType, user?: UserInfo | null) => void
): void;
static setPassword(
username: string,
Expand All @@ -77,10 +72,7 @@ export default class LinuxUser {
groupName: string,
callback: (error: ErrorType, group?: GroupInfo | null) => void
): void;
static removeGroup(
groupName: string,
callback: (error: ErrorType) => void
): void;
static removeGroup(groupName: string, callback: (error: ErrorType) => void): void;
static getGroups(
callback: (error: ErrorType, groups?: GroupInfo[]) => void
): void;
Expand Down Expand Up @@ -112,4 +104,69 @@ export default class LinuxUser {
callback: (error: ErrorType, done?: boolean) => void
): void;
static validateUsername(username: string): boolean;
/** Read-only subset that does not require root privileges. */
static nonRoot: LinuxUserReadOnly;
}

/** Read-only functions that do not require root privileges. */
export interface LinuxUserReadOnly {
getUsers(callback: (error: ErrorType, users?: UserInfo[]) => void): void;
getGroups(callback: (error: ErrorType, groups?: GroupInfo[]) => void): void;
getUserInfo(
username: string,
callback: (error: ErrorType, user?: UserInfo | null) => void
): void;
getUserGroups(
username: string,
callback: (error: ErrorType, groups?: string[]) => void
): void;
getExpiration(
username: string,
callback: (error: ErrorType, data?: UserExpirationInfo) => void
): void;
validateUsername(username: string): boolean;
verifySSHKey(
key: string,
callback: (error: ErrorType, done?: boolean) => void
): void;
promise: LinuxUserPromiseFactory;
}

/** Result of `linuxUser.promise()` -- all methods return Promises. */
export interface LinuxUserPromise {
addUser(args: UserCreationArgs | string): Promise<UserInfo>;
removeUser(username: string): Promise<void>;
getUserGroups(username: string): Promise<string[]>;
getUsers(): Promise<UserInfo[]>;
getUserInfo(username: string): Promise<UserInfo | null>;
setPassword(username: string, password: string): Promise<void>;
addGroup(groupName: string): Promise<GroupInfo>;
removeGroup(groupName: string): Promise<void>;
getGroups(): Promise<GroupInfo[]>;
getGroupInfo(groupName: string): Promise<GroupInfo | null>;
addUserToGroup(username: string, groupName: string): Promise<void>;
getExpiration(username: string): Promise<UserExpirationInfo>;
setExpiration(username: string, args: UserExpirationEditArgs): Promise<any>;
verifySSHKey(key: string): Promise<any>;
addSSHtoUser(username: string, key: string): Promise<boolean>;
validateUsername(username: string): boolean;
}

/** Read-only promise subset (see LinuxUserReadOnly). */
export interface LinuxUserReadOnlyPromise {
getUsers(): Promise<UserInfo[]>;
getGroups(): Promise<GroupInfo[]>;
getUserInfo(username: string): Promise<UserInfo | null>;
getUserGroups(username: string): Promise<string[]>;
getExpiration(username: string): Promise<UserExpirationInfo>;
validateUsername(username: string): boolean;
verifySSHKey(key: string): Promise<any>;
}

export interface LinuxUserPromiseFactory {
(promisifyFn?: (fn: Function) => Function): LinuxUserPromise;
nonRoot(promisifyFn?: (fn: Function) => Function): LinuxUserReadOnlyPromise;
}

/** Non-root import: `import linuxUser from 'linux-user/non-root'`. */
export declare const nonRoot: LinuxUserReadOnly;
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ if (!(process.getuid && process.getuid() === 0)) {
var lib = require("./lib/user");
lib.promise = require("./lib/promise");

// Convenience accessor for the read-only (non-root safe) subset. For an import
// path that also suppresses the root warning, use `require('linux-user/non-root')`.
lib.nonRoot = require("./non-root");

module.exports = lib;
72 changes: 64 additions & 8 deletions lib/promise.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,76 @@
"use strict";

var promise = function (promise_fn) {
var lib = require("./user");
// Functions that follow the (err, result) callback convention and can be
// promisified. `validateUsername` is synchronous (no callback) and must NOT be
// promisified -- util.promisify would inject a callback that is never invoked,
// producing a promise that never settles.
var ASYNC = [
"addUser",
"removeUser",
"getUserGroups",
"getUsers",
"getUserInfo",
"setPassword",
"addGroup",
"removeGroup",
"getGroups",
"getGroupInfo",
"addUserToGroup",
"getExpiration",
"setExpiration",
"verifySSHKey",
"addSSHtoUser",
];

// Functions that are safe to use without root privileges (read-only or operate
// on the calling user). Exposed via `require('linux-user/non-root')`.
var NON_ROOT = [
"getUsers",
"getGroups",
"getUserInfo",
"getUserGroups",
"getExpiration",
"validateUsername",
"verifySSHKey",
];

if (!promise_fn) {
function build(promisifyFn, keys) {
var lib = require("./user");
if (!promisifyFn) {
var util = require("util");
promise_fn = util.promisify;
promisifyFn = util.promisify;
}

var out = {};

Object.keys(lib).forEach(function (key) {
out[key] = promise_fn(lib[key]);
keys.forEach(function (key) {
if (typeof lib[key] !== "function") {
return;
}
if (ASYNC.indexOf(key) !== -1) {
out[key] = promisifyFn(lib[key]);
} else {
// synchronous helpers are passed through unchanged
out[key] = lib[key];
}
});
return out;
}

var promise = function (promisifyFn) {
// Use an explicit key list rather than Object.keys(lib) so properties
// attached at the index level (promise, nonRoot) are not promisified.
return build(promisifyFn, ASYNC.concat(["validateUsername"]));
};

promise.nonRoot = function (promisifyFn) {
var full = promise(promisifyFn);
var out = {};
NON_ROOT.forEach(function (key) {
if (full[key] !== undefined) {
out[key] = full[key];
}
});
return out;
};

module.exports = promise;
module.exports = promise;
Loading
Loading