为什么运行 "npm run <script>" as root 切换用户?

Why does running "npm run <script>" as root switch user?

我在 /app2 中的 alpine 图像 (node:16-alpine) 中设置了一个新项目,结构如下:

- node_modules
  - .bin
    - dummy
- package.json

package.json:

{
  ...
  "scripts": {
    "dummy": "dummy",
  },
  ...
}

假人:

#!/usr/bin/env node

setInterval(() => console.log("."), 1000)

现在,当我 运行 npm run dummy 使用 root 用户而不是 root 用户时,节点命令将 运行 使用拥有项目根目录的任何用户。例如:

/app2 # ls -lah
...    
drwxr-xr-x    3 node2    node        4.0K Jan 17 08:27 .
...

/app2 # whoami
root

/app2 # npm run dummy
...

# in a different terminal:
/app2 # ps x
...
  816 root      0:00 npm run dummy
  827 node2     0:00 node /app2/node_modules/.bin/dummy
...

如果我不使用 root 运行ning npm,则不会发生这种情况(例如:su node && npm run dummy 将 运行 作为 node 用户,而不是 node2).

这是为什么?有谁知道这是否记录在任何地方?或者我如何 运行 root 脚本? (我知道不推荐这样做,但它在 docker 容器内并且仅用于开发)

这发生在 @npmcli/promise-spawn

 const isRoot = process.getuid && process.getuid() === 0
 const { uid, gid } = isRoot ? inferOwner.sync(cwd) : {}

您找不到文档,因为此行为是 removed a while ago

这是在该提交中删除的旧注释,描述了您看到的行为:

Note: When the current user is root, this will use infer-owner to find the owner of the current working directory, and run with that effective uid/gid. Otherwise, it runs as the current user always. (This helps prevent doing git checkouts and such, and leaving root-owned files lying around in user-owned locations.)