@wuyuchentr/run-as-user
v1.0.0
Published
Drop privileges and run a function as another user (requires root). POSIX-only.
Maintainers
Readme
@wuyuchentr/run-as-user
Drop privileges and run a function as another user. Requires root. POSIX-only (Linux, macOS).
Designed for daemon processes that start as root and want to drop to a lower-privileged user.
Install
npm install @wuyuchentr/run-as-userUsage
const { runAs, isRoot } = require('@wuyuchentr/run-as-user');
runAs('nobody', () => {
// This code runs as the 'nobody' user
startServer();
});Forms
// By username
runAs('www-data', () => { ... });
runAs('nobody', () => { ... });
// By UID
runAs(65534, () => { ... });
// By object (no /etc/passwd lookup)
runAs({ uid: 1000, gid: 1000 }, () => { ... });Helpers
isRoot(); // → true if euid === 0How it works
Resolves the target user via /etc/passwd, then in order:
initgroups()— set supplementary groupssetgid()— set primary group IDsetuid()— set user ID (permanent drop)
After setuid() the process cannot regain root. This is intentional.
Notes
- Only works on POSIX with
setuid/setgidsyscalls - The target user must exist in
/etc/passwd(unless using{ uid, gid }form) { uid, gid }form skips supplementary group initialization
