# 权限与沙箱

> atomd 插件怎样声明权限、atomd 授予什么、用户在哪里确认，以及每个插件的虚拟机资源限制。

- 网页：https://dinox.info/guides/atomd-plugins/capabilities
- 本页 Markdown：https://dinox.info/guides/atomd-plugins/capabilities.md
- 全部文档索引：https://dinox.info/llms.txt

插件能做的每一件事都要在 `nsh.json` 的 `capabilities` 里声明。启用插件时，atomd 把声明翻译成人话列给用户看，用户同意后才授予。没有声明、或 atomd 不授予的调用，会以 `ERR_ACCESS_DENIED` 失败。这些检查由 NSH 运行时执行，插件绕不过去。

## 声明

```json title="nsh.json"
"capabilities": {
  "host": ["atomd.note.read", "atomd.note.applyEdits", "atomd.ui.*"],
  "process": {
    "execute": ["codex"],
    "env": ["OPENAI_API_KEY", "HTTPS_PROXY"]
  },
  "fs": {
    "read": ["${dataDir}"],
    "write": ["${dataDir}"]
  },
  "network": {
    "hosts": ["api.example.com"]
  }
}
```

| 键                    | 含义                                                                         | 用户看到的说明                                                |
| -------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------ |
| `host`               | 要调用的 atomd API，写完整名称或前缀加 `*`。见 [Host API](https://dinox.info/guides/atomd-plugins/host-api.md)。 | 「Reads the open note」「Edits the open note (undoable)」等 |
| `process.execute`    | 可以运行的程序名                                                                   | 「Runs codex」                                           |
| `process.env`        | 允许传给子进程的环境变量                                                               | 「Passes on OPENAI\_API\_KEY, …」                        |
| `fs.read`、`fs.write` | 可以读写的目录。`${dataDir}` 是插件自己的数据目录，`${pluginDir}` 是插件安装目录                     | 「Reads files in its data folder」                       |
| `network.hosts`      | 可以访问的域名                                                                    | 「Connects to api.example.com」                          |

这些权限对应的具体接口（`process.run`、`fs/promises`、`fetch`）见 [运行程序、文件与网络](https://dinox.info/guides/atomd-plugins/modules.md)。

## atomd 授予什么

atomd 授予的就是你的声明，但有几条限制：

* `host` 只保留 atomd 真正提供的 API 名称。声明了不存在的名称不会出错，只是不会被授予。
* `windows`、`application`、`webview`、`openUrl` **从不授予**：插件不能开窗口、不能打开网页、不能控制应用本身。
* 子进程只拿到 `HOME`、`TMPDIR`、`LANG` 和 atomd 的 `PATH`。macOS 上 `PATH` 包含 `/opt/homebrew/bin`、`/usr/local/bin` 和 `~/.local/bin`。其他环境变量必须列在 `process.env` 里才会传过去。
* 关闭插件会撤销授权并停掉它的虚拟机。

## 权限变化与重新授权

用户同意的是**某一份**权限声明。插件更新后，如果新版本的声明和用户之前同意的不一样（例如多运行了一个程序、多访问了一个域名），atomd 不会启动它，而是在 **Settings → Plugins** 里把它标为需要确认，列出新增的权限。用户点 **Allow** 后才会启动。

所以：

* 只申请真正需要的权限。权限越少，用户越容易同意，审核也越快。
* 加权限要在 Release 说明里写清楚原因，否则用户会困惑为什么插件突然停了。
* 新的 Host API 名称本身就是新权限。atomd 以后加新 API，旧插件不会悄悄获得访问权。

## 资源限制

每个启用的插件跑在自己的 QuickJS 虚拟机里，有这些上限：

| 限制        | 值      |
| --------- | ------ |
| 内存        | 64 MB  |
| 单次调用的执行时间 | 500 ms |
| 加载时间      | 5 s    |
| 节点数       | 20 000 |

只计算 JavaScript 实际运行的时间。等待子进程输出或 `fetch` 响应这类异步操作不计入。超出限制的虚拟机会被停掉并保持停止，状态显示为失败，直到用户 **Reload**。

长时间计算（比如处理很大的笔记）要拆成小段，用 `await` 或 `setTimeout` 让出执行权，别在一个回调里做完。