Compare commits
38 Commits
239a6c3552
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| cb683c43bb | |||
| 392eafccf2 | |||
| 39856a3060 | |||
| c6f0393c65 | |||
| 1a202986e8 | |||
| dcc91ead9b | |||
| 311d9f4d9f | |||
| 525436d64b | |||
| 36f3c93484 | |||
| 1ac75f429c | |||
| a2b965094d | |||
| 98a75a50d3 | |||
| 4a8a4b01cb | |||
| 95fb9ba820 | |||
| 764ada7c60 | |||
| 81c0a4c289 | |||
| 4e8e264390 | |||
| 21d7a85ba1 | |||
| 7346c80c88 | |||
| 7fd2819a04 | |||
| 98fc3da39c | |||
| be0f194f47 | |||
| 2816f3a862 | |||
| ce79a782b9 | |||
| 63d7fb569e | |||
| 2f149ed1b4 | |||
| 123c73cfc6 | |||
| 79c5f4cd27 | |||
| 61cffae9ca | |||
| 99787e6ded | |||
| 2e38cb8fe2 | |||
| c16149db9d | |||
| b00086816c | |||
| a347908d9f | |||
| bc2c5f8bd6 | |||
| ddaea57f2d | |||
| c186eb24ec | |||
| 0569a5dcf5 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -28,3 +28,9 @@ Thumbs.db
|
|||||||
*.a
|
*.a
|
||||||
*.test
|
*.test
|
||||||
vendor/
|
vendor/
|
||||||
|
|
||||||
|
# Lock files (sub-packages)
|
||||||
|
plugin/package-lock.json
|
||||||
|
|
||||||
|
# Build secret (generated by install.mjs)
|
||||||
|
.build-secret
|
||||||
|
|||||||
209
README.md
209
README.md
@@ -6,132 +6,171 @@
|
|||||||
|
|
||||||
# PaddedCell
|
# PaddedCell
|
||||||
|
|
||||||
OpenClaw plugin for secure password management, safe command execution, and coordinated agent restart.
|
OpenClaw plugin for secure secret management, agent identity management, safe command execution, and coordinated agent restart.
|
||||||
|
|
||||||
|
## ⚠️ Security Model
|
||||||
|
|
||||||
|
> **pcexec + pcguard mitigate light model hallucination / misoperation / prompt forgetting.**
|
||||||
|
> They **do not** defend against malicious attacks.
|
||||||
|
> For stronger security, use **sandbox mode** instead of this plugin.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
### 1. pass_mgr - Password Manager Binary (Go)
|
### 1. secret-mgr — Secret Manager (Go)
|
||||||
|
|
||||||
AES-256-GCM encryption, per-agent key-based encryption/decryption.
|
AES-256-GCM encryption with a **build-time secret** injected at compile time.
|
||||||
|
Secrets are stored per-agent under `pc-pass-store/<agent-id>/<key>.gpg`.
|
||||||
|
|
||||||
|
**Agent commands** (require pcguard — must run through pcexec):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Initialize
|
secret-mgr list # List keys for current agent
|
||||||
pass_mgr admin init [--key-path <path>]
|
secret-mgr get-secret --key <key> # Output secret
|
||||||
|
secret-mgr get-username --key <key> # Output username
|
||||||
# Get password
|
secret-mgr set --key <key> --secret <s> [--username <u>] # Set entry
|
||||||
pass_mgr get <key> [--username]
|
secret-mgr generate --key <key> [--username <u>] # Generate random secret
|
||||||
|
secret-mgr unset --key <key> # Delete entry
|
||||||
# Generate password (agent can use)
|
secret-mgr get <key> # Legacy (maps to get-secret)
|
||||||
pass_mgr generate <key> [--username <user>]
|
|
||||||
|
|
||||||
# Set password (human only)
|
|
||||||
pass_mgr set <key> <password> [--username <user>]
|
|
||||||
|
|
||||||
# Delete password
|
|
||||||
pass_mgr unset <key>
|
|
||||||
|
|
||||||
# Rotate password
|
|
||||||
pass_mgr rotate <key>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Security Features:**
|
**Admin commands** (human-only — rejected if any `AGENT_*` env var is set):
|
||||||
- Agents cannot execute `set` (detected via environment variables)
|
|
||||||
- All operations fail before initialization
|
|
||||||
- Admin password leak detection (monitors messages/tool calls)
|
|
||||||
|
|
||||||
### 2. pcexec - Safe Execution Tool (TypeScript)
|
```bash
|
||||||
|
secret-mgr admin handoff [file] # Export build secret to file (default: pc-pass-store.secret)
|
||||||
Compatible with OpenClaw native exec interface, automatically handles `pass_mgr get` and sanitizes output.
|
secret-mgr admin init-from [file] # Re-encrypt all data from old build secret to current
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { pcexec } from 'pcexec';
|
|
||||||
|
|
||||||
const result = await pcexec('echo $(pass_mgr get mypassword)', {
|
|
||||||
cwd: '/workspace',
|
|
||||||
timeout: 30000,
|
|
||||||
});
|
|
||||||
// Passwords in result.stdout will be replaced with ######
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. safe-restart - Safe Restart Module (TypeScript)
|
### 2. ego-mgr — Agent Identity Manager (Go)
|
||||||
|
|
||||||
Provides agent state management and coordinated restart.
|
Manages agent personal information (name, email, timezone, etc.) stored in `~/.openclaw/ego.json`.
|
||||||
|
|
||||||
**Agent States:**
|
Supports **Agent Scope** (per-agent values) and **Public Scope** (shared by all agents).
|
||||||
- `idle` - Idle
|
|
||||||
- `busy` - Processing messages
|
|
||||||
- `focus` - Focus mode (workflow)
|
|
||||||
- `freeze` - Frozen (not accepting new messages)
|
|
||||||
- `pre-freeze` - Preparing to freeze
|
|
||||||
- `pre-freeze-focus` - Preparing to freeze (focus mode)
|
|
||||||
|
|
||||||
**APIs:**
|
**Commands** (require pcguard — must run through pcexec):
|
||||||
- `POST /query-restart` - Query restart readiness
|
|
||||||
- `POST /restart-result` - Report restart result
|
|
||||||
- `GET /status` - Get all statuses
|
|
||||||
|
|
||||||
**Slash Commands:**
|
```bash
|
||||||
|
ego-mgr add column <name> [--default <val>] # Add agent-scope field
|
||||||
|
ego-mgr add public-column <name> [--default <val>] # Add public-scope field
|
||||||
|
ego-mgr delete <name> # Delete field and all values
|
||||||
|
ego-mgr set <name> <value> # Set field value
|
||||||
|
ego-mgr get <name> # Get field value
|
||||||
|
ego-mgr show # Show all fields and values
|
||||||
|
ego-mgr list columns # List all field names
|
||||||
```
|
```
|
||||||
/padded-cell-ctrl status
|
|
||||||
/padded-cell-ctrl enable pass-mgr|safe-restart
|
### 3. pcguard — Exec Guard (Go)
|
||||||
/padded-cell-ctrl disable pass-mgr|safe-restart
|
|
||||||
|
Validates that a process is running inside a pcexec context by checking environment sentinels (`AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE`). Returns exit code 1 if any check fails.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
pcguard || exit 1
|
||||||
|
# ... rest of script
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 4. pcexec — Safe Execution Tool (TypeScript)
|
||||||
|
|
||||||
|
Drop-in replacement for `exec` that:
|
||||||
|
- Resolves `$(secret-mgr get-secret --key <key>)` and legacy `$(pass_mgr get-secret --key <key>)` inline
|
||||||
|
- Sanitizes all resolved passwords from stdout/stderr
|
||||||
|
- Injects `AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE` environment variables
|
||||||
|
- Appends `$(openclaw path)/bin` to `PATH` (making `pcguard`, `secret-mgr`, and `ego-mgr` available)
|
||||||
|
|
||||||
|
### 5. safe-restart — Coordinated Restart (TypeScript)
|
||||||
|
|
||||||
|
Agent state management and coordinated gateway restart.
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
PaddedCell/
|
PaddedCell/
|
||||||
├── pass_mgr/ # Go password manager binary
|
├── plugin/ # Plugin source (TypeScript)
|
||||||
│ ├── src/
|
│ ├── commands/ # Slash commands
|
||||||
│ │ └── main.go
|
│ ├── core/ # Core modules (safe-restart, status, api)
|
||||||
│ └── go.mod
|
│ ├── hooks/ # Lifecycle hooks
|
||||||
├── pcexec/ # TypeScript safe execution tool
|
│ ├── tools/ # Tool definitions (pcexec)
|
||||||
│ ├── src/
|
│ ├── index.ts # Plugin entry point
|
||||||
│ │ └── index.ts
|
│ ├── openclaw.plugin.json
|
||||||
│ ├── package.json
|
│ ├── package.json
|
||||||
│ └── tsconfig.json
|
│ └── tsconfig.json
|
||||||
├── safe-restart/ # TypeScript safe restart module
|
├── secret-mgr/ # Go secret manager binary
|
||||||
│ ├── src/
|
│ └── src/main.go
|
||||||
│ │ ├── index.ts
|
├── ego-mgr/ # Go agent identity manager binary
|
||||||
│ │ ├── status-manager.ts
|
│ └── src/main.go
|
||||||
│ │ ├── api.ts
|
├── pcguard/ # Go exec guard binary
|
||||||
│ │ ├── safe-restart.ts
|
│ └── src/main.go
|
||||||
│ │ └── slash-commands.ts
|
├── skills/ # Agent skills
|
||||||
│ ├── package.json
|
│ ├── secret-mgr/SKILL.md
|
||||||
│ └── tsconfig.json
|
│ └── ego-mgr/SKILL.md
|
||||||
├── docs/ # Documentation
|
├── dist/padded-cell/ # Build output
|
||||||
├── PROJECT_PLAN.md # Project plan
|
├── install.mjs # Installer
|
||||||
├── AGENT_TASKS.md # Task list
|
└── README.md
|
||||||
├── README.md # This file (English)
|
|
||||||
└── README.zh-CN.md # Chinese version
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install
|
# Install (default: ~/.openclaw)
|
||||||
node install.mjs --install
|
node install.mjs
|
||||||
|
|
||||||
|
# Install with custom openclaw profile path
|
||||||
|
node install.mjs --openclaw-profile-path /path/to/.openclaw
|
||||||
|
|
||||||
|
# Build only (no install)
|
||||||
|
node install.mjs --build-only
|
||||||
|
|
||||||
# Uninstall
|
# Uninstall
|
||||||
node install.mjs --uninstall
|
node install.mjs --uninstall
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
The installer automatically generates a random 32-byte build secret (stored in `.build-secret`, gitignored) and injects it into `secret-mgr` at compile time. Subsequent builds reuse the same secret.
|
||||||
|
|
||||||
> PCEXEC + PCGUARD only mitigate light model hallucination / misoperation / prompt forgetting. They do not defend against malicious attacks. For stronger security, use sandbox mode instead of this plugin.
|
### Install paths
|
||||||
|
|
||||||
|
Priority: `--openclaw-profile-path` → `$OPENCLAW_PATH` → `~/.openclaw`
|
||||||
|
|
||||||
### pass_mgr
|
Binaries → `$(openclaw path)/bin/`, plugin files → `$(openclaw path)/plugins/padded-cell/`.
|
||||||
|
|
||||||
|
## Plugin Update Workflow (admin handoff)
|
||||||
|
|
||||||
|
When you rebuild PaddedCell (which generates a new build secret), existing encrypted data needs re-encryption:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Initialize (required before first use)
|
# 1. Before updating — export current build secret
|
||||||
~/.openclaw/bin/pass_mgr admin init
|
~/.openclaw/bin/secret-mgr admin handoff
|
||||||
|
|
||||||
# Set password
|
# 2. Rebuild & reinstall (generates new .build-secret)
|
||||||
~/.openclaw/bin/pass_mgr set mykey mypassword
|
rm .build-secret
|
||||||
|
node install.mjs
|
||||||
|
|
||||||
# Get password
|
# 3. After updating — re-encrypt data with new secret
|
||||||
~/.openclaw/bin/pass_mgr get mykey
|
~/.openclaw/bin/secret-mgr admin init-from
|
||||||
|
|
||||||
|
# 4. Restart gateway
|
||||||
|
openclaw gateway restart
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Agent sets and gets private passwords (via pcexec)
|
||||||
|
secret-mgr set --key myservice --secret s3cret --username admin
|
||||||
|
secret-mgr get-secret --key myservice
|
||||||
|
secret-mgr get-username --key myservice
|
||||||
|
|
||||||
|
# Shared scope (.public)
|
||||||
|
secret-mgr set --public --key shared-api --secret s3cret
|
||||||
|
secret-mgr list --public
|
||||||
|
secret-mgr get-secret --public --key shared-api
|
||||||
|
|
||||||
|
# Use in shell commands (pcexec resolves and sanitizes)
|
||||||
|
curl -u "$(secret-mgr get-username --key myservice):$(secret-mgr get-secret --key myservice)" https://api.example.com
|
||||||
|
|
||||||
|
# Agent identity management (via pcexec)
|
||||||
|
ego-mgr add column name
|
||||||
|
ego-mgr set name "小智"
|
||||||
|
ego-mgr add public-column timezone --default UTC
|
||||||
|
ego-mgr show
|
||||||
```
|
```
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
279
achieve/REQUIREMENTS_EGO_MGR.md
Normal file
279
achieve/REQUIREMENTS_EGO_MGR.md
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
# PaddedCell 需求更新 — ego-mgr & 重命名
|
||||||
|
|
||||||
|
> 版本:v0.2
|
||||||
|
> 日期:2026-03-24
|
||||||
|
> 状态:待实现
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 重命名:pass_mgr → secret-mgr
|
||||||
|
|
||||||
|
### 1.1 范围
|
||||||
|
所有文档、代码、技能引用中的 `pass_mgr` 统一更名为 `secret-mgr`:
|
||||||
|
|
||||||
|
- 二进制文件名:`pass_mgr` → `secret-mgr`
|
||||||
|
- 命令引用:`pass_mgr <cmd>` → `secret-mgr <cmd>`
|
||||||
|
- 文档:README.md, PROJECT_PLAN.md, SKILL.md 等
|
||||||
|
- 技能目录:`skills/pass-mgr/` → `skills/secret-mgr/`
|
||||||
|
|
||||||
|
### 1.2 命令保持不变
|
||||||
|
```bash
|
||||||
|
secret-mgr list # List keys for current agent
|
||||||
|
secret-mgr get-secret --key <key> # Output secret
|
||||||
|
secret-mgr get-username --key <key> # Output username
|
||||||
|
secret-mgr set --key <key> --secret <s> [--username <u>] # Set entry
|
||||||
|
secret-mgr generate --key <key> [--username <u>] # Generate random secret
|
||||||
|
secret-mgr unset --key <key> # Delete entry
|
||||||
|
secret-mgr get <key> # Legacy (maps to get-secret)
|
||||||
|
secret-mgr admin handoff [file] # Export build secret
|
||||||
|
secret-mgr admin init-from [file] # Re-encrypt data
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 新增 ego-mgr 二进制(Go)
|
||||||
|
|
||||||
|
### 2.1 功能概述
|
||||||
|
`ego-mgr` 管理 Agent 的个人信息(名字、邮箱、出生日期等),支持:
|
||||||
|
- **Agent Scope 字段**:每个 Agent 独立存储,值可不同
|
||||||
|
- **Public Scope 字段**:全局共用,所有 Agent 共享同一值
|
||||||
|
|
||||||
|
### 2.2 数据存储
|
||||||
|
- **文件路径**:`~/.openclaw/ego.json`
|
||||||
|
- **格式**:JSON
|
||||||
|
- **Schema**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"columns": ["col1", "col2", "..."],
|
||||||
|
"public-columns": ["pub-col1", "pub-col2", "..."],
|
||||||
|
"public-scope": {
|
||||||
|
"pub-col1": "value1",
|
||||||
|
"pub-col2": "value2"
|
||||||
|
},
|
||||||
|
"agent-scope": {
|
||||||
|
"agent-id-1": {
|
||||||
|
"col1": "value-x",
|
||||||
|
"col2": "value-y"
|
||||||
|
},
|
||||||
|
"agent-id-2": {
|
||||||
|
"col1": "value-z"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 命令接口
|
||||||
|
|
||||||
|
#### 2.3.0 帮助
|
||||||
|
```bash
|
||||||
|
ego-mgr --help
|
||||||
|
```
|
||||||
|
输出命令使用说明和示例。
|
||||||
|
|
||||||
|
#### 2.3.1 增加字段
|
||||||
|
```bash
|
||||||
|
# Agent Scope 字段
|
||||||
|
ego-mgr add column <column-name> [--default <default-value>]
|
||||||
|
|
||||||
|
# Public Scope 字段
|
||||||
|
ego-mgr add public-column <column-name> [--default <default-value>]
|
||||||
|
```
|
||||||
|
- `--default`:可选,设置默认值(不设置则默认为空字符串)
|
||||||
|
- 字段已存在时返回错误
|
||||||
|
|
||||||
|
### 2.3.2 删除字段
|
||||||
|
```bash
|
||||||
|
ego-mgr delete <column-name>
|
||||||
|
```
|
||||||
|
- 删除指定字段及其所有值(包括 `public-scope` 和所有 `agent-scope` 中的值)
|
||||||
|
- 字段不存在时返回错误
|
||||||
|
|
||||||
|
#### 2.3.3 设置字段值
|
||||||
|
```bash
|
||||||
|
ego-mgr set <column-name> <value>
|
||||||
|
```
|
||||||
|
- 字段必须已存在(通过 `add column` 或 `add public-column` 创建)
|
||||||
|
- 字段不存在时返回错误
|
||||||
|
- 根据字段类型自动写入 `agent-scope` 或 `public-scope`
|
||||||
|
|
||||||
|
#### 2.3.4 查询字段
|
||||||
|
```bash
|
||||||
|
# 获取单个字段值
|
||||||
|
ego-mgr get <column-name>
|
||||||
|
|
||||||
|
# 列出所有字段和值(先 Public 后 Agent Scope)
|
||||||
|
ego-mgr show
|
||||||
|
|
||||||
|
# 仅列出字段名(先 Public 后 Agent Scope)
|
||||||
|
ego-mgr list columns
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 输出示例
|
||||||
|
|
||||||
|
#### ego-mgr show
|
||||||
|
```
|
||||||
|
pub-col1: val1
|
||||||
|
pub-col2: val2
|
||||||
|
...
|
||||||
|
col1: valx
|
||||||
|
col2: valy
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ego-mgr list columns
|
||||||
|
```
|
||||||
|
pub-col1
|
||||||
|
pub-col2
|
||||||
|
...
|
||||||
|
col1
|
||||||
|
col2
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ego-mgr get <column>
|
||||||
|
```
|
||||||
|
<value>
|
||||||
|
```
|
||||||
|
(仅输出值,无额外格式)
|
||||||
|
|
||||||
|
### 2.5 安全约束
|
||||||
|
- **必须由 pcexec 调用**:检测到非 pcexec 环境(缺少 `AGENT_VERIFY` 等环境变量)时拒绝执行
|
||||||
|
- **Agent 隔离**:Agent 只能读写自己的 `agent-scope` 字段,不能访问其他 Agent 的数据
|
||||||
|
- **Public Scope 读取**:所有 Agent 可读取 `public-scope`
|
||||||
|
|
||||||
|
### 2.6 字段命名规则
|
||||||
|
- **字符限制**:无限制(允许空格、特殊字符)
|
||||||
|
- **长度限制**:无限制
|
||||||
|
- **大小写**:区分大小写
|
||||||
|
- **唯一性**:public-column 和 column 名字不能重复(全局唯一)
|
||||||
|
|
||||||
|
### 2.7 初始化逻辑
|
||||||
|
- `ego.json` 不存在时,由 PaddedCell 安装脚本自动创建空结构:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"columns": [],
|
||||||
|
"public-columns": [],
|
||||||
|
"public-scope": {},
|
||||||
|
"agent-scope": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.8 并发安全
|
||||||
|
- 写操作(`add`, `delete`, `set`)必须使用文件锁,防止多 Agent 并发写入导致数据损坏
|
||||||
|
- 读操作(`get`, `show`, `list columns`)无需锁
|
||||||
|
|
||||||
|
### 2.9 Agent 自动注册
|
||||||
|
- **读/写操作时**:如果当前 `agent-id` 不存在于 `agent-scope` 中,自动创建空条目:
|
||||||
|
```json
|
||||||
|
"agent-scope": {
|
||||||
|
"new-agent-id": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **字段验证**:如果 `column-name` 不存在于 `columns` 或 `public-columns` 中,返回错误(退出码 2)
|
||||||
|
|
||||||
|
### 2.10 错误退出码
|
||||||
|
| 退出码 | 含义 |
|
||||||
|
|--------|------|
|
||||||
|
| 0 | 成功 |
|
||||||
|
| 1 | 参数错误 / 用法错误 |
|
||||||
|
| 2 | 字段不存在(column-name 不在 columns 或 public-columns 中) |
|
||||||
|
| 3 | 字段已存在 |
|
||||||
|
| 4 | 权限错误(非 pcexec 环境 / Agent 越权) |
|
||||||
|
| 5 | 文件锁获取失败 |
|
||||||
|
| 6 | JSON 解析/写入错误 |
|
||||||
|
|
||||||
|
### 2.11 值的大小限制
|
||||||
|
- 单字段值长度无限制
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 新增 ego-mgr Skill
|
||||||
|
|
||||||
|
### 3.1 Skill 路径
|
||||||
|
`~/.openclaw/skills/ego-mgr/SKILL.md`
|
||||||
|
|
||||||
|
### 3.2 Skill 功能
|
||||||
|
- 指导 Agent 正确使用 `ego-mgr` 命令
|
||||||
|
- 说明字段管理流程(先 `add column`,再 `set`)
|
||||||
|
- 提供常见用例(设置名字、邮箱、时区等)
|
||||||
|
|
||||||
|
### 3.3 触发条件
|
||||||
|
- 用户请求管理 Agent 个人信息
|
||||||
|
- 用户询问 ego-mgr 用法
|
||||||
|
- 需要存储/读取 Agent 配置信息
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 依赖关系
|
||||||
|
|
||||||
|
```
|
||||||
|
+------------------+
|
||||||
|
| pcexec |
|
||||||
|
+--------+---------+
|
||||||
|
|
|
||||||
|
v
|
||||||
|
+--------+---------+ +------------------+
|
||||||
|
| ego-mgr |<----| ~.openclaw/ |
|
||||||
|
| secret-mgr | | ego.json |
|
||||||
|
+------------------+ +------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
- `ego-mgr` 和 `secret-mgr` 都必须通过 `pcexec` 调用
|
||||||
|
- `pcexec` 负责:
|
||||||
|
- 注入环境变量(`AGENT_VERIFY`, `AGENT_ID`, `AGENT_WORKSPACE`)
|
||||||
|
- 解析并脱敏敏感信息
|
||||||
|
- 验证执行上下文
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 待确认事项
|
||||||
|
|
||||||
|
1. **字段类型**:是否支持字段类型约束(如 email、date、number)?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 实现任务清单
|
||||||
|
|
||||||
|
### M1:重命名 pass_mgr → secret-mgr & 初始化 ego.json
|
||||||
|
- [ ] 重命名二进制文件
|
||||||
|
- [ ] 更新所有文档引用
|
||||||
|
- [ ] 更新 Skill 目录和引用
|
||||||
|
- [ ] 更新 install.mjs 安装脚本
|
||||||
|
- [ ] install.mjs 自动创建空 `ego.json` 结构
|
||||||
|
|
||||||
|
### M1.5:pass_mgr → secret-mgr 数据迁移
|
||||||
|
**迁移步骤**:
|
||||||
|
1. 删除旧的 `pass_mgr` 前,执行:`pass_mgr admin handoff`(导出当前 build secret)
|
||||||
|
2. 安装新的 `secret-mgr` 后,执行:`secret-mgr admin init-from`(用新 secret 重新加密数据)
|
||||||
|
3. 重启 gateway:`openclaw gateway restart`
|
||||||
|
|
||||||
|
### M2:实现 ego-mgr 二进制
|
||||||
|
- [ ] 设计 JSON Schema 和文件结构
|
||||||
|
- [ ] 实现 `--help`
|
||||||
|
- [ ] 实现 `add column` / `add public-column`
|
||||||
|
- [ ] 实现 `delete`
|
||||||
|
- [ ] 实现 `set`
|
||||||
|
- [ ] 实现 `get` / `show` / `list columns`
|
||||||
|
- [ ] 实现 pcexec 环境检测
|
||||||
|
- [ ] 实现 Agent 隔离逻辑
|
||||||
|
- [ ] 实现文件锁(并发安全)
|
||||||
|
- [ ] 实现错误退出码
|
||||||
|
|
||||||
|
### M3:编写 ego-mgr Skill
|
||||||
|
- [ ] 创建 `skills/ego-mgr/SKILL.md`
|
||||||
|
- [ ] 编写使用示例
|
||||||
|
- [ ] 集成到 OpenClaw Skill 系统
|
||||||
|
|
||||||
|
### M4:集成测试
|
||||||
|
- [ ] 测试 ego-mgr 与 pcexec 集成
|
||||||
|
- [ ] 测试多 Agent 隔离
|
||||||
|
- [ ] 测试 Public/Agent Scope 分离
|
||||||
|
- [ ] 测试边界条件(字段不存在、重复添加等)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 验收标准
|
||||||
|
|
||||||
|
1. `secret-mgr` 所有原有功能正常工作,文档更新完成
|
||||||
|
2. `ego-mgr` 支持完整的 CRUD 操作
|
||||||
|
3. `ego-mgr` 只能通过 `pcexec` 调用
|
||||||
|
4. Agent 数据隔离正确,Public Scope 共享正确
|
||||||
|
5. Skill 文档清晰,Agent 能独立使用
|
||||||
@@ -1,14 +1,10 @@
|
|||||||
module pass_mgr
|
module ego-mgr
|
||||||
|
|
||||||
go 1.24.0
|
go 1.24.0
|
||||||
|
|
||||||
require (
|
require github.com/spf13/cobra v1.8.0
|
||||||
github.com/spf13/cobra v1.8.0
|
|
||||||
golang.org/x/term v0.40.0
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // indirect
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
golang.org/x/sys v0.41.0 // indirect
|
|
||||||
)
|
)
|
||||||
@@ -6,9 +6,5 @@ github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
|
|||||||
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
|
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
|
||||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
|
||||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
|
||||||
golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
|
|
||||||
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
517
ego-mgr/src/main.go
Normal file
517
ego-mgr/src/main.go
Normal file
@@ -0,0 +1,517 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"
|
||||||
|
egoFileName = "ego.json"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes per spec
|
||||||
|
const (
|
||||||
|
ExitSuccess = 0
|
||||||
|
ExitUsageError = 1
|
||||||
|
ExitColumnNotFound = 2
|
||||||
|
ExitColumnExists = 3
|
||||||
|
ExitPermission = 4
|
||||||
|
ExitLockFailed = 5
|
||||||
|
ExitJSONError = 6
|
||||||
|
ExitNotFound = 7
|
||||||
|
)
|
||||||
|
|
||||||
|
// EgoData is the on-disk JSON structure
|
||||||
|
type EgoData struct {
|
||||||
|
Columns []string `json:"columns"`
|
||||||
|
PublicColumns []string `json:"public-columns"`
|
||||||
|
PublicScope map[string]string `json:"public-scope"`
|
||||||
|
AgentScope map[string]map[string]string `json:"agent-scope"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveOpenclawPath() string {
|
||||||
|
if p := os.Getenv("OPENCLAW_PATH"); p != "" {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
return filepath.Join(home, ".openclaw")
|
||||||
|
}
|
||||||
|
|
||||||
|
func egoFilePath() string {
|
||||||
|
return filepath.Join(resolveOpenclawPath(), egoFileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentAgentID() string {
|
||||||
|
return os.Getenv("AGENT_ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
func requirePcguard() {
|
||||||
|
if os.Getenv("AGENT_VERIFY") != expectedAgentVerify {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: must be invoked via pcexec (AGENT_VERIFY mismatch)")
|
||||||
|
os.Exit(ExitPermission)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_ID") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_ID not set — must be invoked via pcexec")
|
||||||
|
os.Exit(ExitPermission)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_WORKSPACE") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_WORKSPACE not set — must be invoked via pcexec")
|
||||||
|
os.Exit(ExitPermission)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// readEgoData reads and parses the ego.json file
|
||||||
|
func readEgoData() (*EgoData, error) {
|
||||||
|
fp := egoFilePath()
|
||||||
|
raw, err := os.ReadFile(fp)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
// Return empty structure
|
||||||
|
return &EgoData{
|
||||||
|
Columns: []string{},
|
||||||
|
PublicColumns: []string{},
|
||||||
|
PublicScope: map[string]string{},
|
||||||
|
AgentScope: map[string]map[string]string{},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("failed to read %s: %w", fp, err)
|
||||||
|
}
|
||||||
|
var data EgoData
|
||||||
|
if err := json.Unmarshal(raw, &data); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse %s: %w", fp, err)
|
||||||
|
}
|
||||||
|
// Ensure maps are initialized
|
||||||
|
if data.PublicScope == nil {
|
||||||
|
data.PublicScope = map[string]string{}
|
||||||
|
}
|
||||||
|
if data.AgentScope == nil {
|
||||||
|
data.AgentScope = map[string]map[string]string{}
|
||||||
|
}
|
||||||
|
if data.Columns == nil {
|
||||||
|
data.Columns = []string{}
|
||||||
|
}
|
||||||
|
if data.PublicColumns == nil {
|
||||||
|
data.PublicColumns = []string{}
|
||||||
|
}
|
||||||
|
return &data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeEgoData writes ego data to ego.json with file locking
|
||||||
|
func writeEgoData(data *EgoData) error {
|
||||||
|
fp := egoFilePath()
|
||||||
|
|
||||||
|
// Acquire file lock
|
||||||
|
lockPath := fp + ".lock"
|
||||||
|
lockFile, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: cannot create lock file: %v\n", err)
|
||||||
|
os.Exit(ExitLockFailed)
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
lockFile.Close()
|
||||||
|
os.Remove(lockPath)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: failed to acquire file lock (another process is writing)")
|
||||||
|
os.Exit(ExitLockFailed)
|
||||||
|
}
|
||||||
|
defer syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN)
|
||||||
|
|
||||||
|
raw, err := json.MarshalIndent(data, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal JSON: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.WriteFile(fp, append(raw, '\n'), 0644); err != nil {
|
||||||
|
return fmt.Errorf("failed to write %s: %w", fp, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureAgent ensures the current agent has an entry in agent-scope
|
||||||
|
func ensureAgent(data *EgoData) {
|
||||||
|
agentID := currentAgentID()
|
||||||
|
if _, ok := data.AgentScope[agentID]; !ok {
|
||||||
|
data.AgentScope[agentID] = map[string]string{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// isPublicColumn checks if a column name is in public-columns
|
||||||
|
func isPublicColumn(data *EgoData, name string) bool {
|
||||||
|
for _, c := range data.PublicColumns {
|
||||||
|
if c == name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// isAgentColumn checks if a column name is in columns (agent scope)
|
||||||
|
func isAgentColumn(data *EgoData, name string) bool {
|
||||||
|
for _, c := range data.Columns {
|
||||||
|
if c == name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// columnExists checks if a column name exists in either scope
|
||||||
|
func columnExists(data *EgoData, name string) bool {
|
||||||
|
return isPublicColumn(data, name) || isAgentColumn(data, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
rootCmd := &cobra.Command{
|
||||||
|
Use: "ego-mgr",
|
||||||
|
Short: "Agent identity/profile manager for OpenClaw",
|
||||||
|
Long: `ego-mgr manages agent personal information (name, email, timezone, etc.).
|
||||||
|
|
||||||
|
Fields can be Agent Scope (per-agent) or Public Scope (shared by all agents).
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
ego-mgr add column name
|
||||||
|
ego-mgr add public-column timezone --default UTC
|
||||||
|
ego-mgr set name "小智"
|
||||||
|
ego-mgr get name
|
||||||
|
ego-mgr show
|
||||||
|
ego-mgr list columns
|
||||||
|
ego-mgr delete name`,
|
||||||
|
}
|
||||||
|
|
||||||
|
rootCmd.AddCommand(addCmd(), deleteCmd(), setCmd(), getCmd(), showCmd(), listCmd(), lookupCmd())
|
||||||
|
|
||||||
|
if err := rootCmd.Execute(); err != nil {
|
||||||
|
os.Exit(ExitUsageError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func addCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "add",
|
||||||
|
Short: "Add a new column",
|
||||||
|
}
|
||||||
|
cmd.AddCommand(addColumnCmd(), addPublicColumnCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func addColumnCmd() *cobra.Command {
|
||||||
|
var defaultVal string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "column <column-name>",
|
||||||
|
Short: "Add an agent-scope column",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' already exists\n", colName)
|
||||||
|
os.Exit(ExitColumnExists)
|
||||||
|
}
|
||||||
|
|
||||||
|
data.Columns = append(data.Columns, colName)
|
||||||
|
|
||||||
|
// Set default value for all existing agents
|
||||||
|
if defaultVal != "" {
|
||||||
|
for agentID := range data.AgentScope {
|
||||||
|
data.AgentScope[agentID][colName] = defaultVal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&defaultVal, "default", "", "Default value for the column")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func addPublicColumnCmd() *cobra.Command {
|
||||||
|
var defaultVal string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "public-column <column-name>",
|
||||||
|
Short: "Add a public-scope column",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' already exists\n", colName)
|
||||||
|
os.Exit(ExitColumnExists)
|
||||||
|
}
|
||||||
|
|
||||||
|
data.PublicColumns = append(data.PublicColumns, colName)
|
||||||
|
if defaultVal != "" {
|
||||||
|
data.PublicScope[colName] = defaultVal
|
||||||
|
} else {
|
||||||
|
data.PublicScope[colName] = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&defaultVal, "default", "", "Default value for the column")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "delete <column-name>",
|
||||||
|
Short: "Delete a column and all its values",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' does not exist\n", colName)
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove from public-columns if present
|
||||||
|
if isPublicColumn(data, colName) {
|
||||||
|
newCols := []string{}
|
||||||
|
for _, c := range data.PublicColumns {
|
||||||
|
if c != colName {
|
||||||
|
newCols = append(newCols, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.PublicColumns = newCols
|
||||||
|
delete(data.PublicScope, colName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove from agent columns if present
|
||||||
|
if isAgentColumn(data, colName) {
|
||||||
|
newCols := []string{}
|
||||||
|
for _, c := range data.Columns {
|
||||||
|
if c != colName {
|
||||||
|
newCols = append(newCols, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.Columns = newCols
|
||||||
|
// Remove from all agent scopes
|
||||||
|
for agentID := range data.AgentScope {
|
||||||
|
delete(data.AgentScope[agentID], colName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func setCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "set <column-name> <value>",
|
||||||
|
Short: "Set a field value",
|
||||||
|
Args: cobra.ExactArgs(2),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
value := args[1]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' does not exist (use 'ego-mgr add column' or 'ego-mgr add public-column' first)\n", colName)
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-register agent
|
||||||
|
ensureAgent(data)
|
||||||
|
|
||||||
|
if isPublicColumn(data, colName) {
|
||||||
|
data.PublicScope[colName] = value
|
||||||
|
} else {
|
||||||
|
agentID := currentAgentID()
|
||||||
|
data.AgentScope[agentID][colName] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeEgoData(data); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get <column-name>",
|
||||||
|
Short: "Get a field value",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
colName := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !columnExists(data, colName) {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column '%s' does not exist\n", colName)
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-register agent
|
||||||
|
ensureAgent(data)
|
||||||
|
|
||||||
|
if isPublicColumn(data, colName) {
|
||||||
|
fmt.Print(data.PublicScope[colName])
|
||||||
|
} else {
|
||||||
|
agentID := currentAgentID()
|
||||||
|
fmt.Print(data.AgentScope[agentID][colName])
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func showCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "show",
|
||||||
|
Short: "Show all fields and values",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-register agent
|
||||||
|
ensureAgent(data)
|
||||||
|
agentID := currentAgentID()
|
||||||
|
|
||||||
|
// Print public scope first
|
||||||
|
for _, col := range data.PublicColumns {
|
||||||
|
val := data.PublicScope[col]
|
||||||
|
fmt.Printf("%s: %s\n", col, val)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then agent scope
|
||||||
|
for _, col := range data.Columns {
|
||||||
|
val := ""
|
||||||
|
if agentData, ok := data.AgentScope[agentID]; ok {
|
||||||
|
val = agentData[col]
|
||||||
|
}
|
||||||
|
fmt.Printf("%s: %s\n", col, val)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func listCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Short: "List information",
|
||||||
|
}
|
||||||
|
cmd.AddCommand(listColumnsCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func listColumnsCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "columns",
|
||||||
|
Short: "List all column names",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print public columns first
|
||||||
|
for _, col := range data.PublicColumns {
|
||||||
|
fmt.Println(col)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then agent columns
|
||||||
|
for _, col := range data.Columns {
|
||||||
|
fmt.Println(col)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "lookup <username>",
|
||||||
|
Short: "Look up an agent ID by default-username",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
username := args[0]
|
||||||
|
|
||||||
|
data, err := readEgoData()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(ExitJSONError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify default-username column exists
|
||||||
|
if !isAgentColumn(data, "default-username") {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: column 'default-username' does not exist\n")
|
||||||
|
os.Exit(ExitColumnNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
for agentID, agentData := range data.AgentScope {
|
||||||
|
if agentData["default-username"] == username {
|
||||||
|
fmt.Print(agentID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: no agent found with default-username '%s'\n", username)
|
||||||
|
os.Exit(ExitNotFound)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
102
index.js
102
index.js
@@ -1,102 +0,0 @@
|
|||||||
// PaddedCell Plugin for OpenClaw
|
|
||||||
// Registers pcexec and safe_restart tools
|
|
||||||
|
|
||||||
const { pcexec, pcexecSync } = require('./pcexec/dist/index.js');
|
|
||||||
const {
|
|
||||||
safeRestart,
|
|
||||||
createSafeRestartTool,
|
|
||||||
StatusManager,
|
|
||||||
createApiServer,
|
|
||||||
startApiServer,
|
|
||||||
SlashCommandHandler
|
|
||||||
} = require('./safe-restart/dist/index.js');
|
|
||||||
|
|
||||||
// Plugin registration function
|
|
||||||
function register(api, config) {
|
|
||||||
const logger = api.logger || { info: console.log, error: console.error };
|
|
||||||
|
|
||||||
logger.info('PaddedCell plugin initializing...');
|
|
||||||
|
|
||||||
// Register pcexec tool - pass a FACTORY function that receives context
|
|
||||||
api.registerTool((ctx) => {
|
|
||||||
console.log(`[PaddedCell] pcexec factory called with ctx:`, JSON.stringify(ctx, null, 2));
|
|
||||||
const agentId = ctx.agentId;
|
|
||||||
const workspaceDir = ctx.workspaceDir;
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: 'pcexec',
|
|
||||||
description: 'Safe exec with password sanitization',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
command: { type: 'string', description: 'Command to execute' },
|
|
||||||
cwd: { type: 'string', description: 'Working directory' },
|
|
||||||
timeout: { type: 'number', description: 'Timeout in milliseconds' },
|
|
||||||
},
|
|
||||||
required: ['command'],
|
|
||||||
},
|
|
||||||
async execute(_id, params) {
|
|
||||||
const command = params.command;
|
|
||||||
if (!command) {
|
|
||||||
throw new Error('Missing required parameter: command');
|
|
||||||
}
|
|
||||||
console.log(`[PaddedCell] pcexec execute: agentId=${agentId}, workspaceDir=${workspaceDir}`);
|
|
||||||
const result = await pcexec(command, {
|
|
||||||
cwd: params.cwd || workspaceDir,
|
|
||||||
timeout: params.timeout,
|
|
||||||
env: {
|
|
||||||
AGENT_ID: agentId || '',
|
|
||||||
AGENT_WORKSPACE: workspaceDir || '',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
// Format output for OpenClaw tool response
|
|
||||||
let output = result.stdout;
|
|
||||||
if (result.stderr) {
|
|
||||||
output += result.stderr;
|
|
||||||
}
|
|
||||||
return { content: [{ type: 'text', text: output }] };
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// Register safe_restart tool - pass a FACTORY function that receives context
|
|
||||||
api.registerTool((ctx) => {
|
|
||||||
const agentId = ctx.agentId;
|
|
||||||
const sessionKey = ctx.sessionKey;
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: 'safe_restart',
|
|
||||||
description: 'Safe coordinated restart of OpenClaw gateway',
|
|
||||||
parameters: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
rollback: { type: 'string', description: 'Rollback script path' },
|
|
||||||
log: { type: 'string', description: 'Log file path' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
async execute(_id, params) {
|
|
||||||
return await safeRestart({
|
|
||||||
agentId: agentId,
|
|
||||||
sessionKey: sessionKey,
|
|
||||||
rollback: params.rollback,
|
|
||||||
log: params.log,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
logger.info('PaddedCell plugin initialized');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Export for OpenClaw
|
|
||||||
module.exports = { register };
|
|
||||||
|
|
||||||
// Also export individual modules for direct use
|
|
||||||
module.exports.pcexec = pcexec;
|
|
||||||
module.exports.pcexecSync = pcexecSync;
|
|
||||||
module.exports.safeRestart = safeRestart;
|
|
||||||
module.exports.createSafeRestartTool = createSafeRestartTool;
|
|
||||||
module.exports.StatusManager = StatusManager;
|
|
||||||
module.exports.createApiServer = createApiServer;
|
|
||||||
module.exports.startApiServer = startApiServer;
|
|
||||||
module.exports.SlashCommandHandler = SlashCommandHandler;
|
|
||||||
813
install.mjs
813
install.mjs
@@ -1,19 +1,21 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PaddedCell Plugin Installer
|
* PaddedCell Plugin Installer v0.3.0
|
||||||
*
|
|
||||||
* Usage:
|
|
||||||
* node install.mjs
|
|
||||||
* node install.mjs --prefix /usr/local
|
|
||||||
* node install.mjs --build-only
|
|
||||||
* node install.mjs --skip-check
|
|
||||||
* node install.mjs --uninstall
|
|
||||||
* node install.mjs --uninstall --prefix /usr/local
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
import { existsSync, mkdirSync, copyFileSync, writeFileSync, chmodSync, readdirSync, statSync } from 'fs';
|
import {
|
||||||
|
existsSync,
|
||||||
|
mkdirSync,
|
||||||
|
copyFileSync,
|
||||||
|
chmodSync,
|
||||||
|
readdirSync,
|
||||||
|
rmSync,
|
||||||
|
readFileSync,
|
||||||
|
writeFileSync,
|
||||||
|
} from 'fs';
|
||||||
|
import { randomBytes } from 'crypto';
|
||||||
import { dirname, join, resolve } from 'path';
|
import { dirname, join, resolve } from 'path';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
import { homedir, platform } from 'os';
|
import { homedir, platform } from 'os';
|
||||||
@@ -21,534 +23,405 @@ import { homedir, platform } from 'os';
|
|||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
const __dirname = resolve(dirname(__filename));
|
const __dirname = resolve(dirname(__filename));
|
||||||
|
|
||||||
// Plugin configuration - matches directory name in dist/
|
|
||||||
const PLUGIN_NAME = 'padded-cell';
|
const PLUGIN_NAME = 'padded-cell';
|
||||||
const DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
|
const SRC_DIST_DIR = join(__dirname, 'dist', PLUGIN_NAME);
|
||||||
|
|
||||||
// Parse arguments
|
|
||||||
const args = process.argv.slice(2);
|
const args = process.argv.slice(2);
|
||||||
const options = {
|
const options = {
|
||||||
prefix: null,
|
openclawProfilePath: null,
|
||||||
buildOnly: args.includes('--build-only'),
|
buildOnly: args.includes('--build-only'),
|
||||||
skipCheck: args.includes('--skip-check'),
|
skipCheck: args.includes('--skip-check'),
|
||||||
verbose: args.includes('--verbose') || args.includes('-v'),
|
verbose: args.includes('--verbose') || args.includes('-v'),
|
||||||
uninstall: args.includes('--uninstall'),
|
uninstall: args.includes('--uninstall'),
|
||||||
|
installOnly: args.includes('--install'),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Parse --prefix value
|
const profileIdx = args.indexOf('--openclaw-profile-path');
|
||||||
const prefixIndex = args.indexOf('--prefix');
|
if (profileIdx !== -1 && args[profileIdx + 1]) {
|
||||||
if (prefixIndex !== -1 && args[prefixIndex + 1]) {
|
options.openclawProfilePath = resolve(args[profileIdx + 1]);
|
||||||
options.prefix = resolve(args[prefixIndex + 1]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Colors for output
|
function resolveOpenclawPath() {
|
||||||
const colors = {
|
if (options.openclawProfilePath) return options.openclawProfilePath;
|
||||||
reset: '\x1b[0m',
|
if (process.env.OPENCLAW_PATH) return resolve(process.env.OPENCLAW_PATH);
|
||||||
red: '\x1b[31m',
|
return join(homedir(), '.openclaw');
|
||||||
green: '\x1b[32m',
|
}
|
||||||
yellow: '\x1b[33m',
|
|
||||||
blue: '\x1b[34m',
|
const c = {
|
||||||
cyan: '\x1b[36m',
|
reset: '\x1b[0m', red: '\x1b[31m', green: '\x1b[32m',
|
||||||
|
yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m',
|
||||||
};
|
};
|
||||||
|
function log(msg, color = 'reset') { console.log(`${c[color]}${msg}${c.reset}`); }
|
||||||
|
function logStep(n, total, msg) { log(`[${n}/${total}] ${msg}`, 'cyan'); }
|
||||||
|
function logOk(msg) { log(` ✓ ${msg}`, 'green'); }
|
||||||
|
function logWarn(msg) { log(` ⚠ ${msg}`, 'yellow'); }
|
||||||
|
function logErr(msg) { log(` ✗ ${msg}`, 'red'); }
|
||||||
|
|
||||||
function log(message, color = 'reset') {
|
function exec(command, opts = {}) {
|
||||||
console.log(`${colors[color]}${message}${colors.reset}`);
|
return execSync(command, {
|
||||||
}
|
|
||||||
|
|
||||||
function logStep(step, message) {
|
|
||||||
log(`[${step}/6] ${message}`, 'cyan');
|
|
||||||
}
|
|
||||||
|
|
||||||
function logSuccess(message) {
|
|
||||||
log(` ✓ ${message}`, 'green');
|
|
||||||
}
|
|
||||||
|
|
||||||
function logWarning(message) {
|
|
||||||
log(` ⚠ ${message}`, 'yellow');
|
|
||||||
}
|
|
||||||
|
|
||||||
function logError(message) {
|
|
||||||
log(` ✗ ${message}`, 'red');
|
|
||||||
}
|
|
||||||
|
|
||||||
function exec(command, options = {}) {
|
|
||||||
const defaultOptions = {
|
|
||||||
cwd: __dirname,
|
cwd: __dirname,
|
||||||
stdio: options.silent ? 'pipe' : 'inherit',
|
stdio: opts.silent ? 'pipe' : 'inherit',
|
||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
};
|
...opts,
|
||||||
return execSync(command, { ...defaultOptions, ...options });
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// OpenClaw config helpers
|
function getOpenclawConfig(key, def = undefined) {
|
||||||
function getOpenclawConfig(pathKey, defaultValue = undefined) {
|
|
||||||
try {
|
try {
|
||||||
const out = execSync(`openclaw config get ${pathKey} --json 2>/dev/null || echo "undefined"`, {
|
const out = exec(`openclaw config get ${key} --json 2>/dev/null || echo "undefined"`, { silent: true }).trim();
|
||||||
encoding: 'utf8',
|
if (out === 'undefined' || out === '') return def;
|
||||||
cwd: __dirname
|
|
||||||
}).trim();
|
|
||||||
if (out === 'undefined' || out === '') return defaultValue;
|
|
||||||
return JSON.parse(out);
|
return JSON.parse(out);
|
||||||
} catch {
|
} catch { return def; }
|
||||||
return defaultValue;
|
}
|
||||||
}
|
function setOpenclawConfig(key, value) {
|
||||||
|
exec(`openclaw config set ${key} '${JSON.stringify(value)}' --json`, { silent: true });
|
||||||
|
}
|
||||||
|
function unsetOpenclawConfig(key) {
|
||||||
|
try { exec(`openclaw config unset ${key}`, { silent: true }); } catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setOpenclawConfig(pathKey, value) {
|
|
||||||
const cmd = `openclaw config set ${pathKey} '${JSON.stringify(value)}' --json`;
|
|
||||||
execSync(cmd, { cwd: __dirname, encoding: 'utf8' });
|
|
||||||
}
|
|
||||||
|
|
||||||
function unsetOpenclawConfig(pathKey) {
|
|
||||||
try {
|
|
||||||
execSync(`openclaw config unset ${pathKey}`, { cwd: __dirname, encoding: 'utf8' });
|
|
||||||
} catch {
|
|
||||||
// Ignore errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Copy directory recursively
|
|
||||||
function copyDir(src, dest) {
|
function copyDir(src, dest) {
|
||||||
mkdirSync(dest, { recursive: true });
|
mkdirSync(dest, { recursive: true });
|
||||||
const entries = readdirSync(src, { withFileTypes: true });
|
for (const entry of readdirSync(src, { withFileTypes: true })) {
|
||||||
|
const s = join(src, entry.name);
|
||||||
for (const entry of entries) {
|
const d = join(dest, entry.name);
|
||||||
const srcPath = join(src, entry.name);
|
if (entry.name === 'node_modules') continue;
|
||||||
const destPath = join(dest, entry.name);
|
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
|
||||||
|
|
||||||
if (entry.isDirectory()) {
|
|
||||||
copyDir(srcPath, destPath);
|
|
||||||
} else {
|
|
||||||
copyFileSync(srcPath, destPath);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Step 1: Environment Detection
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
function detectEnvironment() {
|
function detectEnvironment() {
|
||||||
logStep(1, 'Detecting environment...');
|
logStep(1, 6, 'Detecting environment...');
|
||||||
|
const env = { platform: platform(), nodeVersion: null, goVersion: null };
|
||||||
const env = {
|
try { env.nodeVersion = exec('node --version', { silent: true }).trim(); logOk(`Node.js ${env.nodeVersion}`); } catch { logErr('Node.js not found'); }
|
||||||
platform: platform(),
|
try { env.goVersion = exec('go version', { silent: true }).trim(); logOk(`Go: ${env.goVersion}`); } catch { logErr('Go not found'); }
|
||||||
nodeVersion: null,
|
try { logOk(`openclaw at ${exec('which openclaw', { silent: true }).trim()}`); } catch { logWarn('openclaw CLI not in PATH'); }
|
||||||
goVersion: null,
|
|
||||||
openclawDir: join(homedir(), '.openclaw'),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check Node.js
|
|
||||||
try {
|
|
||||||
env.nodeVersion = exec('node --version', { silent: true }).trim();
|
|
||||||
logSuccess(`Node.js ${env.nodeVersion}`);
|
|
||||||
} catch {
|
|
||||||
logError('Node.js not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check Go
|
|
||||||
try {
|
|
||||||
env.goVersion = exec('go version', { silent: true }).trim();
|
|
||||||
logSuccess(`Go ${env.goVersion}`);
|
|
||||||
} catch {
|
|
||||||
logError('Go not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check openclaw
|
|
||||||
try {
|
|
||||||
const path = exec('which openclaw', { silent: true }).trim();
|
|
||||||
logSuccess(`openclaw at ${path}`);
|
|
||||||
|
|
||||||
// Try to find openclaw config dir
|
|
||||||
const home = homedir();
|
|
||||||
const possibleDirs = [
|
|
||||||
join(home, '.openclaw'),
|
|
||||||
join(home, '.config', 'openclaw'),
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const dir of possibleDirs) {
|
|
||||||
if (existsSync(dir)) {
|
|
||||||
env.openclawDir = dir;
|
|
||||||
logSuccess(`openclaw config dir: ${dir}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
logWarning('openclaw CLI not found in PATH');
|
|
||||||
}
|
|
||||||
|
|
||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkDependencies(env) {
|
function checkDeps(env) {
|
||||||
if (options.skipCheck) {
|
if (options.skipCheck) { logStep(2, 6, 'Skipping dep checks'); return; }
|
||||||
logWarning('Skipping dependency checks');
|
logStep(2, 6, 'Checking dependencies...');
|
||||||
return true;
|
let fail = false;
|
||||||
}
|
if (!env.nodeVersion || parseInt(env.nodeVersion.slice(1)) < 18) { logErr('Node.js 18+ required'); fail = true; }
|
||||||
|
if (!env.goVersion) { logErr('Go 1.22+ required'); fail = true; }
|
||||||
logStep(2, 'Checking dependencies...');
|
if (fail) { log('\nInstall missing deps and retry.', 'red'); process.exit(1); }
|
||||||
|
logOk('All deps OK');
|
||||||
let hasErrors = false;
|
|
||||||
|
|
||||||
if (!env.nodeVersion) {
|
|
||||||
logError('Node.js is required. Please install Node.js 18+');
|
|
||||||
hasErrors = true;
|
|
||||||
} else {
|
|
||||||
const majorVersion = parseInt(env.nodeVersion.slice(1).split('.')[0]);
|
|
||||||
if (majorVersion < 18) {
|
|
||||||
logError(`Node.js 18+ required, found ${env.nodeVersion}`);
|
|
||||||
hasErrors = true;
|
|
||||||
} else {
|
|
||||||
logSuccess(`Node.js version OK`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!env.goVersion) {
|
|
||||||
logError('Go is required. Please install Go 1.22+');
|
|
||||||
hasErrors = true;
|
|
||||||
} else {
|
|
||||||
logSuccess(`Go version OK`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasErrors) {
|
|
||||||
log('\nPlease install missing dependencies and try again.', 'red');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
function ensureBuildSecret() {
|
||||||
// Step 3: Build Components
|
const secretFile = join(__dirname, '.build-secret');
|
||||||
// ============================================================================
|
if (existsSync(secretFile)) {
|
||||||
|
const existing = readFileSync(secretFile, 'utf8').trim();
|
||||||
async function buildComponents(env) {
|
if (existing.length >= 32) {
|
||||||
logStep(3, 'Building components...');
|
logOk('Reusing existing build secret');
|
||||||
|
return existing;
|
||||||
// Build pass_mgr
|
|
||||||
log(' Building pass_mgr (Go)...', 'blue');
|
|
||||||
try {
|
|
||||||
const passMgrDir = join(__dirname, 'pass_mgr');
|
|
||||||
exec('go mod tidy', { cwd: passMgrDir, silent: !options.verbose });
|
|
||||||
exec('go build -o dist/pass_mgr src/main.go', { cwd: passMgrDir, silent: !options.verbose });
|
|
||||||
|
|
||||||
const binaryPath = join(passMgrDir, 'dist', 'pass_mgr');
|
|
||||||
if (!existsSync(binaryPath)) {
|
|
||||||
throw new Error('pass_mgr binary not found after build');
|
|
||||||
}
|
}
|
||||||
chmodSync(binaryPath, 0o755);
|
|
||||||
logSuccess('pass_mgr built successfully');
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to build pass_mgr: ${err.message}`);
|
|
||||||
throw err;
|
|
||||||
}
|
}
|
||||||
|
const secret = randomBytes(32).toString('hex');
|
||||||
|
writeFileSync(secretFile, secret + '\n', { mode: 0o600 });
|
||||||
|
logOk('Generated new build secret');
|
||||||
|
return secret;
|
||||||
|
}
|
||||||
|
|
||||||
// Build pcexec
|
async function build() {
|
||||||
log(' Building pcexec (TypeScript)...', 'blue');
|
logStep(3, 6, 'Building components...');
|
||||||
try {
|
|
||||||
const pcexecDir = join(__dirname, 'pcexec');
|
|
||||||
exec('npm install', { cwd: pcexecDir, silent: !options.verbose });
|
|
||||||
exec('npm run build', { cwd: pcexecDir, silent: !options.verbose });
|
|
||||||
logSuccess('pcexec built successfully');
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to build pcexec: ${err.message}`);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build safe-restart
|
const buildSecret = ensureBuildSecret();
|
||||||
log(' Building safe-restart (TypeScript)...', 'blue');
|
|
||||||
try {
|
rmSync(SRC_DIST_DIR, { recursive: true, force: true });
|
||||||
const safeRestartDir = join(__dirname, 'safe-restart');
|
|
||||||
exec('npm install', { cwd: safeRestartDir, silent: !options.verbose });
|
log(' Building secret-mgr...', 'blue');
|
||||||
exec('npm run build', { cwd: safeRestartDir, silent: !options.verbose });
|
const pmDir = join(__dirname, 'secret-mgr');
|
||||||
logSuccess('safe-restart built successfully');
|
exec('go mod tidy', { cwd: pmDir, silent: !options.verbose });
|
||||||
} catch (err) {
|
const ldflags = `-X main.buildSecret=${buildSecret}`;
|
||||||
logError(`Failed to build safe-restart: ${err.message}`);
|
exec(`go build -ldflags "${ldflags}" -o dist/secret-mgr src/main.go`, { cwd: pmDir, silent: !options.verbose });
|
||||||
throw err;
|
chmodSync(join(pmDir, 'dist', 'secret-mgr'), 0o755);
|
||||||
|
logOk('secret-mgr');
|
||||||
|
|
||||||
|
log(' Building ego-mgr...', 'blue');
|
||||||
|
const emDir = join(__dirname, 'ego-mgr');
|
||||||
|
exec('go mod tidy', { cwd: emDir, silent: !options.verbose });
|
||||||
|
exec('go build -o dist/ego-mgr src/main.go', { cwd: emDir, silent: !options.verbose });
|
||||||
|
chmodSync(join(emDir, 'dist', 'ego-mgr'), 0o755);
|
||||||
|
logOk('ego-mgr');
|
||||||
|
|
||||||
|
log(' Building pcguard...', 'blue');
|
||||||
|
const pgDir = join(__dirname, 'pcguard');
|
||||||
|
exec('go mod tidy', { cwd: pgDir, silent: !options.verbose });
|
||||||
|
exec('go build -o dist/pcguard src/main.go', { cwd: pgDir, silent: !options.verbose });
|
||||||
|
chmodSync(join(pgDir, 'dist', 'pcguard'), 0o755);
|
||||||
|
logOk('pcguard');
|
||||||
|
|
||||||
|
log(' Building lock-mgr...', 'blue');
|
||||||
|
const lmDir = join(__dirname, 'lock-mgr');
|
||||||
|
exec('go mod tidy', { cwd: lmDir, silent: !options.verbose });
|
||||||
|
exec('go build -o dist/lock-mgr .', { cwd: lmDir, silent: !options.verbose });
|
||||||
|
chmodSync(join(lmDir, 'dist', 'lock-mgr'), 0o755);
|
||||||
|
logOk('lock-mgr');
|
||||||
|
|
||||||
|
log(' Building plugin...', 'blue');
|
||||||
|
const pluginDir = join(__dirname, 'plugin');
|
||||||
|
exec('npm install', { cwd: pluginDir, silent: !options.verbose });
|
||||||
|
exec('npx tsc', { cwd: pluginDir, silent: !options.verbose });
|
||||||
|
logOk('plugin');
|
||||||
|
|
||||||
|
const skillsSrc = join(__dirname, 'skills');
|
||||||
|
const skillsDist = join(SRC_DIST_DIR, 'skills');
|
||||||
|
if (existsSync(skillsSrc)) {
|
||||||
|
copyDir(skillsSrc, skillsDist);
|
||||||
|
logOk('skills copied to dist/padded-cell/skills');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
function handoffSecretIfPossible(openclawPath) {
|
||||||
// Step 4: Install Components
|
// Check both old (pass_mgr) and new (secret-mgr) binary names
|
||||||
// ============================================================================
|
let passMgrPath = join(openclawPath, 'bin', 'secret-mgr');
|
||||||
|
if (!existsSync(passMgrPath)) {
|
||||||
|
passMgrPath = join(openclawPath, 'bin', 'pass_mgr');
|
||||||
|
}
|
||||||
|
if (!existsSync(passMgrPath)) return null;
|
||||||
|
|
||||||
async function installComponents(env) {
|
const storeA = join(openclawPath, 'pc-pass-store');
|
||||||
if (options.buildOnly) {
|
const storeB = join(openclawPath, 'pc-secret-store');
|
||||||
logStep(4, 'Skipping installation (--build-only)');
|
if (!existsSync(storeA) && !existsSync(storeB)) return null;
|
||||||
|
|
||||||
|
const secretFile = join(openclawPath, 'pc-pass-store.secret');
|
||||||
|
try {
|
||||||
|
exec(`${passMgrPath} admin handoff ${secretFile}`, { silent: !options.verbose });
|
||||||
|
logOk(`handoff secret → ${secretFile}`);
|
||||||
|
return secretFile;
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`handoff failed: ${err.message}`);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
logStep(4, 'Installing components...');
|
|
||||||
|
|
||||||
const installDir = options.prefix || env.openclawDir;
|
|
||||||
const binDir = join(installDir, 'bin');
|
|
||||||
|
|
||||||
log(` Install directory: ${installDir}`, 'blue');
|
|
||||||
log(` Binary directory: ${binDir}`, 'blue');
|
|
||||||
log(` Dist directory: ${DIST_DIR}`, 'blue');
|
|
||||||
|
|
||||||
// Create dist/padded-cell directory and copy plugin files
|
|
||||||
log(' Copying plugin files to dist/padded-cell...', 'blue');
|
|
||||||
mkdirSync(DIST_DIR, { recursive: true });
|
|
||||||
|
|
||||||
// Copy pcexec
|
|
||||||
copyDir(join(__dirname, 'pcexec'), join(DIST_DIR, 'pcexec'));
|
|
||||||
logSuccess('Copied pcexec to dist/padded-cell/');
|
|
||||||
|
|
||||||
// Copy safe-restart
|
|
||||||
copyDir(join(__dirname, 'safe-restart'), join(DIST_DIR, 'safe-restart'));
|
|
||||||
logSuccess('Copied safe-restart to dist/padded-cell/');
|
|
||||||
|
|
||||||
// Create root index.js entry point (copy from source)
|
|
||||||
copyFileSync(join(__dirname, 'index.js'), join(DIST_DIR, 'index.js'));
|
|
||||||
logSuccess('Copied index.js entry point');
|
|
||||||
|
|
||||||
// Copy openclaw.plugin.json from source
|
|
||||||
copyFileSync(join(__dirname, 'openclaw.plugin.json'), join(DIST_DIR, 'openclaw.plugin.json'));
|
|
||||||
logSuccess('Copied openclaw.plugin.json');
|
|
||||||
|
|
||||||
// Create bin directory and install pass_mgr binary
|
|
||||||
mkdirSync(binDir, { recursive: true });
|
|
||||||
|
|
||||||
log(' Installing pass_mgr binary...', 'blue');
|
|
||||||
const passMgrSource = join(__dirname, 'pass_mgr', 'dist', 'pass_mgr');
|
|
||||||
const passMgrDest = join(binDir, 'pass_mgr');
|
|
||||||
copyFileSync(passMgrSource, passMgrDest);
|
|
||||||
chmodSync(passMgrDest, 0o755);
|
|
||||||
logSuccess(`pass_mgr installed to ${passMgrDest}`);
|
|
||||||
|
|
||||||
return { passMgrPath: passMgrDest };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
function clearInstallTargets(openclawPath) {
|
||||||
// Step 5: Configuration
|
const binDir = join(openclawPath, 'bin');
|
||||||
// ============================================================================
|
for (const name of ['pass_mgr', 'secret-mgr', 'ego-mgr', 'pcguard', 'lock-mgr']) {
|
||||||
|
const p = join(binDir, name);
|
||||||
|
if (existsSync(p)) { rmSync(p, { force: true }); logOk(`Removed ${p}`); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
|
if (existsSync(destDir)) { rmSync(destDir, { recursive: true, force: true }); logOk(`Removed ${destDir}`); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupConfig(openclawPath) {
|
||||||
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
|
const skillsDir = join(openclawPath, 'skills');
|
||||||
|
try {
|
||||||
|
const allow = getOpenclawConfig('plugins.allow', []);
|
||||||
|
const idx = allow.indexOf(PLUGIN_NAME);
|
||||||
|
if (idx !== -1) {
|
||||||
|
allow.splice(idx, 1);
|
||||||
|
setOpenclawConfig('plugins.allow', allow);
|
||||||
|
logOk('Removed from allow list');
|
||||||
|
}
|
||||||
|
|
||||||
|
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
|
||||||
|
logOk('Removed plugin entry');
|
||||||
|
|
||||||
|
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||||
|
const pidx = paths.indexOf(destDir);
|
||||||
|
if (pidx !== -1) {
|
||||||
|
paths.splice(pidx, 1);
|
||||||
|
setOpenclawConfig('plugins.load.paths', paths);
|
||||||
|
logOk('Removed from load paths');
|
||||||
|
}
|
||||||
|
|
||||||
|
const skillEntries = ['pcexec', 'safe-restart', 'safe_restart', 'pass-mgr', 'secret-mgr', 'ego-mgr'];
|
||||||
|
for (const sk of skillEntries) {
|
||||||
|
const p = join(skillsDir, sk);
|
||||||
|
if (existsSync(p)) {
|
||||||
|
rmSync(p, { recursive: true, force: true });
|
||||||
|
logOk(`Removed skill ${p}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`Config cleanup: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function install() {
|
||||||
|
if (options.buildOnly) { logStep(4, 6, 'Skipping install (--build-only)'); return null; }
|
||||||
|
logStep(4, 6, 'Installing...');
|
||||||
|
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
const binDir = join(openclawPath, 'bin');
|
||||||
|
const pluginsDir = join(openclawPath, 'plugins');
|
||||||
|
const destDir = join(pluginsDir, PLUGIN_NAME);
|
||||||
|
const skillsDir = join(openclawPath, 'skills');
|
||||||
|
const distSkillsDir = join(SRC_DIST_DIR, 'skills');
|
||||||
|
|
||||||
|
log(` OpenClaw path: ${openclawPath}`, 'blue');
|
||||||
|
|
||||||
|
// update/reinstall path: remove old install first
|
||||||
|
if (existsSync(destDir) || existsSync(join(binDir, 'pass_mgr')) || existsSync(join(binDir, 'secret-mgr')) || existsSync(join(binDir, 'pcguard'))) {
|
||||||
|
logWarn('Existing install detected, uninstalling before install...');
|
||||||
|
handoffSecretIfPossible(openclawPath);
|
||||||
|
clearInstallTargets(openclawPath);
|
||||||
|
cleanupConfig(openclawPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });
|
||||||
|
copyDir(SRC_DIST_DIR, destDir);
|
||||||
|
|
||||||
|
copyFileSync(join(__dirname, 'plugin', 'openclaw.plugin.json'), join(destDir, 'openclaw.plugin.json'));
|
||||||
|
copyFileSync(join(__dirname, 'plugin', 'package.json'), join(destDir, 'package.json'));
|
||||||
|
logOk(`Plugin files → ${destDir}`);
|
||||||
|
|
||||||
|
exec('npm install --omit=dev', { cwd: destDir, silent: !options.verbose });
|
||||||
|
logOk('Runtime deps installed');
|
||||||
|
|
||||||
|
mkdirSync(binDir, { recursive: true });
|
||||||
|
const bins = [
|
||||||
|
{ name: 'secret-mgr', src: join(__dirname, 'secret-mgr', 'dist', 'secret-mgr') },
|
||||||
|
{ name: 'ego-mgr', src: join(__dirname, 'ego-mgr', 'dist', 'ego-mgr') },
|
||||||
|
{ name: 'pcguard', src: join(__dirname, 'pcguard', 'dist', 'pcguard') },
|
||||||
|
{ name: 'lock-mgr', src: join(__dirname, 'lock-mgr', 'dist', 'lock-mgr') },
|
||||||
|
];
|
||||||
|
for (const b of bins) {
|
||||||
|
const dest = join(binDir, b.name);
|
||||||
|
copyFileSync(b.src, dest);
|
||||||
|
chmodSync(dest, 0o755);
|
||||||
|
logOk(`${b.name} → ${dest}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only copy dist/padded-cell/skills to ~/.openclaw/skills
|
||||||
|
mkdirSync(skillsDir, { recursive: true });
|
||||||
|
if (existsSync(distSkillsDir)) {
|
||||||
|
for (const entry of readdirSync(distSkillsDir, { withFileTypes: true })) {
|
||||||
|
const s = join(distSkillsDir, entry.name);
|
||||||
|
const d = join(skillsDir, entry.name);
|
||||||
|
rmSync(d, { recursive: true, force: true });
|
||||||
|
entry.isDirectory() ? copyDir(s, d) : copyFileSync(s, d);
|
||||||
|
logOk(`skill synced → ${d}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize ego.json if it doesn't exist
|
||||||
|
const egoJsonPath = join(openclawPath, 'ego.json');
|
||||||
|
if (!existsSync(egoJsonPath)) {
|
||||||
|
const defaultEgo = {
|
||||||
|
columns: ['default-username', 'name', 'discord-id', 'email', 'role', 'position', 'date-of-birth', 'agent-id', 'gender'],
|
||||||
|
'public-columns': ['git-host', 'keycloak-host'],
|
||||||
|
'public-scope': {},
|
||||||
|
'agent-scope': {},
|
||||||
|
};
|
||||||
|
writeFileSync(egoJsonPath, JSON.stringify(defaultEgo, null, 2) + '\n', { mode: 0o644 });
|
||||||
|
logOk('Created ego.json');
|
||||||
|
} else {
|
||||||
|
logOk('ego.json already exists');
|
||||||
|
}
|
||||||
|
|
||||||
|
// if prior encrypted store exists, run init-from once new binary is installed
|
||||||
|
const hasStore = existsSync(join(openclawPath, 'pc-pass-store')) || existsSync(join(openclawPath, 'pc-secret-store'));
|
||||||
|
const secretFile = join(openclawPath, 'pc-pass-store.secret');
|
||||||
|
if (hasStore && existsSync(secretFile)) {
|
||||||
|
const passMgrPath = join(binDir, 'secret-mgr');
|
||||||
|
try {
|
||||||
|
exec(`${passMgrPath} admin init-from ${secretFile}`, { silent: !options.verbose });
|
||||||
|
logOk('init-from completed from handoff secret');
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`init-from failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { binDir, destDir };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function configure() {
|
||||||
|
if (options.buildOnly) { logStep(5, 6, 'Skipping config'); return; }
|
||||||
|
logStep(5, 6, 'Configuring OpenClaw...');
|
||||||
|
|
||||||
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
const destDir = join(openclawPath, 'plugins', PLUGIN_NAME);
|
||||||
|
const secretMgrPath = join(openclawPath, 'bin', 'secret-mgr');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const paths = getOpenclawConfig('plugins.load.paths', []);
|
||||||
|
if (!paths.includes(destDir)) { paths.push(destDir); setOpenclawConfig('plugins.load.paths', paths); }
|
||||||
|
logOk(`plugins.load.paths includes ${destDir}`);
|
||||||
|
|
||||||
|
const allow = getOpenclawConfig('plugins.allow', []);
|
||||||
|
if (!allow.includes(PLUGIN_NAME)) { allow.push(PLUGIN_NAME); setOpenclawConfig('plugins.allow', allow); }
|
||||||
|
logOk(`plugins.allow includes ${PLUGIN_NAME}`);
|
||||||
|
|
||||||
|
const entryPath = `plugins.entries.${PLUGIN_NAME}`;
|
||||||
|
const existingEnabled = getOpenclawConfig(`${entryPath}.enabled`, undefined);
|
||||||
|
if (existingEnabled === undefined) setOpenclawConfig(`${entryPath}.enabled`, true);
|
||||||
|
|
||||||
|
const cfgPath = `${entryPath}.config`;
|
||||||
|
const existingCfgEnabled = getOpenclawConfig(`${cfgPath}.enabled`, undefined);
|
||||||
|
if (existingCfgEnabled === undefined) setOpenclawConfig(`${cfgPath}.enabled`, true);
|
||||||
|
|
||||||
|
const existingSecretMgr = getOpenclawConfig(`${cfgPath}.secretMgrPath`, undefined);
|
||||||
|
if (existingSecretMgr === undefined) setOpenclawConfig(`${cfgPath}.secretMgrPath`, secretMgrPath);
|
||||||
|
|
||||||
|
const existingProfile = getOpenclawConfig(`${cfgPath}.openclawProfilePath`, undefined);
|
||||||
|
if (existingProfile === undefined) setOpenclawConfig(`${cfgPath}.openclawProfilePath`, openclawPath);
|
||||||
|
|
||||||
|
logOk('Plugin entry configured (set missing defaults only)');
|
||||||
|
} catch (err) {
|
||||||
|
logWarn(`Config failed: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function summary() {
|
||||||
|
logStep(6, 6, 'Done!');
|
||||||
|
console.log('');
|
||||||
|
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||||
|
log('║ PaddedCell v0.3.0 Install Complete ║', 'cyan');
|
||||||
|
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||||
|
|
||||||
async function configure(env) {
|
|
||||||
if (options.buildOnly) {
|
if (options.buildOnly) {
|
||||||
logStep(5, 'Skipping configuration (--build-only)');
|
log('\nBuild-only — binaries not installed.', 'yellow');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
logStep(5, 'Configuration...');
|
|
||||||
|
|
||||||
const installDir = options.prefix || env.openclawDir;
|
|
||||||
const passMgrPath = join(installDir, 'bin', 'pass_mgr');
|
|
||||||
|
|
||||||
// Check if already initialized
|
|
||||||
const adminKeyDir = join(homedir(), '.pass_mgr');
|
|
||||||
const configPath = join(adminKeyDir, 'config.json');
|
|
||||||
|
|
||||||
if (existsSync(configPath)) {
|
|
||||||
logSuccess('pass_mgr already initialized');
|
|
||||||
} else {
|
|
||||||
log(' pass_mgr not initialized yet.', 'yellow');
|
|
||||||
log(` Run "${passMgrPath} admin init" manually after installation.`, 'cyan');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configure OpenClaw
|
|
||||||
log('\n Configuring OpenClaw plugin...', 'blue');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. Add plugin path to plugins.load.paths FIRST (required for validation)
|
|
||||||
const currentPaths = getOpenclawConfig('plugins.load.paths', []);
|
|
||||||
log(` Current paths: ${JSON.stringify(currentPaths)}`, 'blue');
|
|
||||||
log(` DIST_DIR: ${DIST_DIR}`, 'blue');
|
|
||||||
if (!currentPaths.includes(DIST_DIR)) {
|
|
||||||
currentPaths.push(DIST_DIR);
|
|
||||||
log(` Adding plugin path...`, 'blue');
|
|
||||||
try {
|
|
||||||
setOpenclawConfig('plugins.load.paths', currentPaths);
|
|
||||||
logSuccess(`Added ${DIST_DIR} to plugins.load.paths`);
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to set paths: ${err.message}`);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log(' Plugin path already in plugins.load.paths', 'green');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Add to plugins.allow (after path is set)
|
|
||||||
const allowList = getOpenclawConfig('plugins.allow', []);
|
|
||||||
if (!allowList.includes(PLUGIN_NAME)) {
|
|
||||||
allowList.push(PLUGIN_NAME);
|
|
||||||
setOpenclawConfig('plugins.allow', allowList);
|
|
||||||
logSuccess(`Added '${PLUGIN_NAME}' to plugins.allow`);
|
|
||||||
} else {
|
|
||||||
log(' Already in plugins.allow', 'green');
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Add plugin entry
|
|
||||||
const plugins = getOpenclawConfig('plugins', {});
|
|
||||||
plugins.entries = plugins.entries || {};
|
|
||||||
plugins.entries[PLUGIN_NAME] = {
|
|
||||||
enabled: true,
|
|
||||||
config: {
|
|
||||||
enabled: true,
|
|
||||||
passMgrPath: passMgrPath,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
setOpenclawConfig('plugins', plugins);
|
|
||||||
logSuccess(`Configured ${PLUGIN_NAME} plugin entry`);
|
|
||||||
} catch (err) {
|
|
||||||
logWarning(`Failed to configure OpenClaw: ${err.message}`);
|
|
||||||
log(' Please manually configure:', 'yellow');
|
|
||||||
log(` openclaw config set plugins.allow --json '[..., "${PLUGIN_NAME}"]'`, 'cyan');
|
|
||||||
log(` openclaw config set plugins.load.paths --json '[..., "${DIST_DIR}"]'`, 'cyan');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Step 6: Print Summary
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
function printSummary(env, passMgrPath) {
|
|
||||||
logStep(6, 'Installation Summary');
|
|
||||||
|
|
||||||
console.log('');
|
console.log('');
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
log('Next steps:', 'blue');
|
||||||
log('║ PaddedCell Installation Complete ║', 'cyan');
|
log(' 1. openclaw gateway restart', 'cyan');
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
|
||||||
console.log('');
|
|
||||||
|
|
||||||
if (options.buildOnly) {
|
|
||||||
log('Build-only mode - binaries built but not installed', 'yellow');
|
|
||||||
console.log('');
|
|
||||||
log('Built artifacts:', 'blue');
|
|
||||||
log(` • pass_mgr: ${join(__dirname, 'pass_mgr', 'dist', 'pass_mgr')}`, 'reset');
|
|
||||||
log(` • pcexec: ${join(__dirname, 'pcexec', 'dist')}`, 'reset');
|
|
||||||
log(` • safe-restart: ${join(__dirname, 'safe-restart', 'dist')}`, 'reset');
|
|
||||||
} else {
|
|
||||||
log('Installed components:', 'blue');
|
|
||||||
log(` • pass_mgr binary: ${passMgrPath}`, 'reset');
|
|
||||||
log(` • Plugin files: ${DIST_DIR}`, 'reset');
|
|
||||||
console.log('');
|
|
||||||
|
|
||||||
log('Next steps:', 'blue');
|
|
||||||
console.log('');
|
|
||||||
log('1. Initialize pass_mgr (required before first use):', 'yellow');
|
|
||||||
log(` ${passMgrPath} admin init`, 'cyan');
|
|
||||||
console.log('');
|
|
||||||
log('2. Test pass_mgr:', 'yellow');
|
|
||||||
log(` ${passMgrPath} set test_key mypass`, 'cyan');
|
|
||||||
log(` ${passMgrPath} get test_key`, 'cyan');
|
|
||||||
console.log('');
|
|
||||||
log('3. Restart OpenClaw gateway:', 'yellow');
|
|
||||||
log(' openclaw gateway restart', 'cyan');
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('');
|
console.log('');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
async function uninstall() {
|
||||||
// Uninstall
|
log('Uninstalling PaddedCell...', 'cyan');
|
||||||
// ============================================================================
|
const openclawPath = resolveOpenclawPath();
|
||||||
|
handoffSecretIfPossible(openclawPath);
|
||||||
async function uninstall(env) {
|
clearInstallTargets(openclawPath);
|
||||||
logStep(1, 'Uninstalling PaddedCell...');
|
cleanupConfig(openclawPath);
|
||||||
|
log('\nRun: openclaw gateway restart', 'yellow');
|
||||||
const installDir = options.prefix || env.openclawDir || join(homedir(), '.openclaw');
|
|
||||||
const passMgrBinary = join(installDir, 'bin', 'pass_mgr');
|
|
||||||
|
|
||||||
// Remove pass_mgr binary
|
|
||||||
if (existsSync(passMgrBinary)) {
|
|
||||||
try {
|
|
||||||
execSync(`rm -f "${passMgrBinary}"`, { silent: true });
|
|
||||||
logSuccess(`Removed ${passMgrBinary}`);
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to remove ${passMgrBinary}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove dist/padded-cell directory
|
|
||||||
if (existsSync(DIST_DIR)) {
|
|
||||||
try {
|
|
||||||
execSync(`rm -rf "${DIST_DIR}"`, { silent: true });
|
|
||||||
logSuccess(`Removed ${DIST_DIR}`);
|
|
||||||
} catch (err) {
|
|
||||||
logError(`Failed to remove ${DIST_DIR}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove OpenClaw configuration
|
|
||||||
log('\n Removing OpenClaw configuration...', 'blue');
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Remove from plugins.allow
|
|
||||||
const allowList = getOpenclawConfig('plugins.allow', []);
|
|
||||||
const idx = allowList.indexOf(PLUGIN_NAME);
|
|
||||||
if (idx !== -1) {
|
|
||||||
allowList.splice(idx, 1);
|
|
||||||
setOpenclawConfig('plugins.allow', allowList);
|
|
||||||
logSuccess(`Removed '${PLUGIN_NAME}' from plugins.allow`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove plugin entry
|
|
||||||
unsetOpenclawConfig(`plugins.entries.${PLUGIN_NAME}`);
|
|
||||||
logSuccess(`Removed ${PLUGIN_NAME} plugin entry`);
|
|
||||||
|
|
||||||
// Remove from plugins.load.paths
|
|
||||||
const currentPaths = getOpenclawConfig('plugins.load.paths', []);
|
|
||||||
const pathIdx = currentPaths.indexOf(DIST_DIR);
|
|
||||||
if (pathIdx !== -1) {
|
|
||||||
currentPaths.splice(pathIdx, 1);
|
|
||||||
setOpenclawConfig('plugins.load.paths', currentPaths);
|
|
||||||
logSuccess(`Removed plugin path from plugins.load.paths`);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
logWarning(`Failed to update OpenClaw config: ${err.message}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for admin key directory
|
|
||||||
const adminKeyDir = join(homedir(), '.pass_mgr');
|
|
||||||
if (existsSync(adminKeyDir)) {
|
|
||||||
log('\n⚠️ Admin key directory found:', 'yellow');
|
|
||||||
log(` ${adminKeyDir}`, 'cyan');
|
|
||||||
log(' This contains your encryption keys. Remove manually if desired.', 'yellow');
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('');
|
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
|
||||||
log('║ PaddedCell Uninstall Complete ║', 'cyan');
|
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
|
||||||
console.log('');
|
|
||||||
log('Restart OpenClaw gateway:', 'yellow');
|
|
||||||
log(' openclaw gateway restart', 'cyan');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// Main
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
console.log('');
|
console.log('');
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'cyan');
|
log('╔══════════════════════════════════════════════╗', 'cyan');
|
||||||
log('║ PaddedCell Plugin Installer v0.1.0 ║', 'cyan');
|
log('║ PaddedCell Plugin Installer v0.3.0 ║', 'cyan');
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'cyan');
|
log('╚══════════════════════════════════════════════╝', 'cyan');
|
||||||
console.log('');
|
console.log('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const env = detectEnvironment();
|
const env = detectEnvironment();
|
||||||
|
|
||||||
// Handle uninstall
|
|
||||||
if (options.uninstall) {
|
if (options.uninstall) {
|
||||||
await uninstall(env);
|
await uninstall();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
checkDependencies(env);
|
checkDeps(env);
|
||||||
await buildComponents(env);
|
await build();
|
||||||
const result = await installComponents(env);
|
|
||||||
await configure(env);
|
if (!options.buildOnly) {
|
||||||
printSummary(env, result?.passMgrPath);
|
await install();
|
||||||
process.exit(0);
|
await configure();
|
||||||
|
}
|
||||||
|
|
||||||
|
summary();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log('');
|
log(`\nInstallation failed: ${err.message}`, 'red');
|
||||||
log('╔════════════════════════════════════════════════════════╗', 'red');
|
|
||||||
log('║ Installation Failed ║', 'red');
|
|
||||||
log('╚════════════════════════════════════════════════════════╝', 'red');
|
|
||||||
console.log('');
|
|
||||||
log(`Error: ${err.message}`, 'red');
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3
lock-mgr/go.mod
Normal file
3
lock-mgr/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module lock-mgr
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
380
lock-mgr/main.go
Normal file
380
lock-mgr/main.go
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LockEntry struct {
|
||||||
|
Locked bool `json:"locked"`
|
||||||
|
Key string `json:"key,omitempty"`
|
||||||
|
Time string `json:"time,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LockFile map[string]*LockEntry
|
||||||
|
|
||||||
|
// heldLock tracks the meta-lock currently held by this process so it can be
|
||||||
|
// released on panic, signal, or any other unexpected exit.
|
||||||
|
var (
|
||||||
|
heldMu sync.Mutex
|
||||||
|
heldMgrPath string
|
||||||
|
heldMgrKey string
|
||||||
|
)
|
||||||
|
|
||||||
|
func setHeldLock(path, key string) {
|
||||||
|
heldMu.Lock()
|
||||||
|
heldMgrPath = path
|
||||||
|
heldMgrKey = key
|
||||||
|
heldMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearHeldLock() {
|
||||||
|
heldMu.Lock()
|
||||||
|
heldMgrPath = ""
|
||||||
|
heldMgrKey = ""
|
||||||
|
heldMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanupMgrLock releases the meta-lock if this process still holds it.
|
||||||
|
// Safe to call multiple times.
|
||||||
|
func cleanupMgrLock() {
|
||||||
|
heldMu.Lock()
|
||||||
|
path := heldMgrPath
|
||||||
|
key := heldMgrKey
|
||||||
|
heldMu.Unlock()
|
||||||
|
|
||||||
|
if path == "" || key == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lf, err := readLockFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry := lf[path]
|
||||||
|
if entry != nil && entry.Key == key {
|
||||||
|
delete(lf, path)
|
||||||
|
_ = writeLockFile(path, lf)
|
||||||
|
}
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateUUID() (string, error) {
|
||||||
|
b := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
b[6] = (b[6] & 0x0f) | 0x40 // version 4
|
||||||
|
b[8] = (b[8] & 0x3f) | 0x80 // variant bits
|
||||||
|
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLockFile(path string) (LockFile, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("read lock file: %w", err)
|
||||||
|
}
|
||||||
|
if len(data) == 0 {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
var lf LockFile
|
||||||
|
if err := json.Unmarshal(data, &lf); err != nil {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
if lf == nil {
|
||||||
|
return make(LockFile), nil
|
||||||
|
}
|
||||||
|
return lf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLockFile(path string, lf LockFile) error {
|
||||||
|
data, err := json.MarshalIndent(lf, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("marshal lock file: %w", err)
|
||||||
|
}
|
||||||
|
return os.WriteFile(path, data, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquireMgrLock implements steps 3-8: acquire the meta-lock on the JSON file itself.
|
||||||
|
// Returns the mgr-key on success.
|
||||||
|
func acquireMgrLock(mgrPath string) (string, error) {
|
||||||
|
// Step 3: generate mgr-key once
|
||||||
|
mgrKey, err := generateUUID()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Step 4: record current time
|
||||||
|
startTime := time.Now()
|
||||||
|
|
||||||
|
// Steps 5-6: spin until the meta-lock is free or owned by us
|
||||||
|
for {
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
entry := lf[mgrPath]
|
||||||
|
if entry == nil || !entry.Locked || entry.Key == mgrKey {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Since(startTime) > 5*time.Second {
|
||||||
|
return "", fmt.Errorf("timeout waiting to acquire manager lock")
|
||||||
|
}
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 7: write locked=true, key=mgrKey
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if lf[mgrPath] == nil {
|
||||||
|
lf[mgrPath] = &LockEntry{}
|
||||||
|
}
|
||||||
|
lf[mgrPath].Locked = true
|
||||||
|
lf[mgrPath].Key = mgrKey
|
||||||
|
if err := writeLockFile(mgrPath, lf); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 8: verify we actually won the race
|
||||||
|
lf2, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if lf2[mgrPath] != nil && lf2[mgrPath].Key == mgrKey {
|
||||||
|
setHeldLock(mgrPath, mgrKey)
|
||||||
|
return mgrKey, nil
|
||||||
|
}
|
||||||
|
// Lost the race; go back to step 4 (keep same mgrKey, reset timer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// releaseMgrLock removes the meta-lock entry and writes the file.
|
||||||
|
func releaseMgrLock(mgrPath string) error {
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
err = writeLockFile(mgrPath, lf)
|
||||||
|
if err == nil {
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdAcquire(mgrPath, filePath, key string) error {
|
||||||
|
// Steps 3-8: acquire meta-lock
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 9: record start time for file-lock wait timeout
|
||||||
|
startTime := time.Now()
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Step 10: read current file lock state
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := lf[filePath]
|
||||||
|
xLocked := entry != nil && entry.Locked
|
||||||
|
xKey := ""
|
||||||
|
if entry != nil {
|
||||||
|
xKey = entry.Key
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 11: if locked by someone else, wait and retry
|
||||||
|
if xLocked && xKey != key {
|
||||||
|
if time.Since(startTime) > 30*time.Second {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return fmt.Errorf("timeout waiting to acquire lock on %s", filePath)
|
||||||
|
}
|
||||||
|
// Release meta-lock while sleeping so others can proceed
|
||||||
|
if err := releaseMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
// Re-acquire meta-lock before next read
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 12: not locked (or already owned by caller's key) — acquire
|
||||||
|
if lf[filePath] == nil {
|
||||||
|
lf[filePath] = &LockEntry{}
|
||||||
|
}
|
||||||
|
lf[filePath].Locked = true
|
||||||
|
lf[filePath].Key = key
|
||||||
|
lf[filePath].Time = time.Now().UTC().Format(time.RFC3339)
|
||||||
|
|
||||||
|
// Step 13: delete meta-lock entry and write atomically
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
if err := writeLockFile(mgrPath, lf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
clearHeldLock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdRelease(mgrPath, filePath, key string) error {
|
||||||
|
// Steps 3-8: acquire meta-lock
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := lf[filePath]
|
||||||
|
xLocked := entry != nil && entry.Locked
|
||||||
|
xKey := ""
|
||||||
|
if entry != nil {
|
||||||
|
xKey = entry.Key
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 14: validate preconditions
|
||||||
|
if !xLocked {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return fmt.Errorf("file %s is not locked", filePath)
|
||||||
|
}
|
||||||
|
if xKey != key {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return fmt.Errorf("key does not match the lock key for %s", filePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 15: delete file lock and meta-lock, write
|
||||||
|
delete(lf, filePath)
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
err = writeLockFile(mgrPath, lf)
|
||||||
|
if err == nil {
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdForceUnlock(mgrPath, filePath string) error {
|
||||||
|
// Steps 3-8: acquire meta-lock
|
||||||
|
if _, err := acquireMgrLock(mgrPath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
lf, err := readLockFile(mgrPath)
|
||||||
|
if err != nil {
|
||||||
|
_ = releaseMgrLock(mgrPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove file lock and meta-lock unconditionally
|
||||||
|
delete(lf, filePath)
|
||||||
|
delete(lf, mgrPath)
|
||||||
|
err = writeLockFile(mgrPath, lf)
|
||||||
|
if err == nil {
|
||||||
|
clearHeldLock()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func run() error {
|
||||||
|
// cleanupMgrLock runs on normal return AND on panic (defer unwinds through panics).
|
||||||
|
// os.Exit bypasses defer, so we keep os.Exit only in main() after run() returns.
|
||||||
|
defer cleanupMgrLock()
|
||||||
|
|
||||||
|
action := ""
|
||||||
|
if len(os.Args) >= 2 {
|
||||||
|
action = os.Args[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
if action == "force-unlock" && len(os.Args) < 3 {
|
||||||
|
return fmt.Errorf("usage: lock-mgr force-unlock <file>")
|
||||||
|
}
|
||||||
|
if (action == "acquire" || action == "release") && len(os.Args) < 4 {
|
||||||
|
return fmt.Errorf("usage: lock-mgr %s <file> <key>", action)
|
||||||
|
}
|
||||||
|
if action == "" || (action != "acquire" && action != "release" && action != "force-unlock") {
|
||||||
|
return fmt.Errorf("usage: lock-mgr <acquire|release> <file> <key>\n lock-mgr force-unlock <file>")
|
||||||
|
}
|
||||||
|
|
||||||
|
fileArg := os.Args[2]
|
||||||
|
key := ""
|
||||||
|
if action != "force-unlock" {
|
||||||
|
key = os.Args[3]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 1: resolve tool directory and locate (or create) the lock file
|
||||||
|
execPath, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot determine executable path: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
toolDir := filepath.Dir(execPath)
|
||||||
|
rawMgrPath := filepath.Join(toolDir, "..", ".lock-mgr.json")
|
||||||
|
|
||||||
|
// Step 2: get absolute paths
|
||||||
|
mgrPath, err := filepath.Abs(rawMgrPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot resolve lock file path: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath, err := filepath.Abs(fileArg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cannot resolve file path: %w", err)
|
||||||
|
}
|
||||||
|
if _, statErr := os.Stat(filePath); os.IsNotExist(statErr) {
|
||||||
|
filePath = fileArg
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure lock file exists
|
||||||
|
if _, statErr := os.Stat(mgrPath); os.IsNotExist(statErr) {
|
||||||
|
if writeErr := os.WriteFile(mgrPath, []byte("{}"), 0644); writeErr != nil {
|
||||||
|
return fmt.Errorf("cannot create lock file: %w", writeErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch action {
|
||||||
|
case "acquire":
|
||||||
|
return cmdAcquire(mgrPath, filePath, key)
|
||||||
|
case "release":
|
||||||
|
return cmdRelease(mgrPath, filePath, key)
|
||||||
|
case "force-unlock":
|
||||||
|
return cmdForceUnlock(mgrPath, filePath)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Signal handler: release meta-lock on SIGINT / SIGTERM before exiting.
|
||||||
|
// This covers Ctrl+C and process termination while the lock is held.
|
||||||
|
sigCh := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
go func() {
|
||||||
|
<-sigCh
|
||||||
|
cleanupMgrLock()
|
||||||
|
os.Exit(130)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := run(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
{
|
|
||||||
"id": "padded-cell",
|
|
||||||
"name": "PaddedCell",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"description": "Secure password management, safe execution, and coordinated restart",
|
|
||||||
"entry": "./index.js",
|
|
||||||
"configSchema": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"enabled": { "type": "boolean", "default": true },
|
|
||||||
"passMgrPath": { "type": "string", "default": "/root/.openclaw/bin/pass_mgr" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,533 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/aes"
|
|
||||||
"crypto/cipher"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
"golang.org/x/term"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
DefaultAlgorithm = "AES-256-GCM"
|
|
||||||
AdminKeyDir = ".pass_mgr"
|
|
||||||
AdminKeyFile = ".priv"
|
|
||||||
SecretsDirName = ".secrets"
|
|
||||||
)
|
|
||||||
|
|
||||||
// EncryptedData represents the structure of encrypted password file
|
|
||||||
type EncryptedData struct {
|
|
||||||
Algorithm string `json:"algorithm"`
|
|
||||||
Nonce string `json:"nonce"`
|
|
||||||
Data string `json:"data"`
|
|
||||||
User string `json:"user,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config holds admin key configuration
|
|
||||||
type Config struct {
|
|
||||||
KeyHash string `json:"key_hash"`
|
|
||||||
Algorithm string `json:"algorithm"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
workspaceDir string
|
|
||||||
agentID string
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
rootCmd := &cobra.Command{
|
|
||||||
Use: "pass_mgr",
|
|
||||||
Short: "Password manager for OpenClaw agents",
|
|
||||||
Long: `A secure password management tool using AES-256-GCM encryption.`,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get environment variables
|
|
||||||
workspaceDir = os.Getenv("AGENT_WORKSPACE")
|
|
||||||
agentID = os.Getenv("AGENT_ID")
|
|
||||||
|
|
||||||
// Commands
|
|
||||||
rootCmd.AddCommand(getCmd())
|
|
||||||
rootCmd.AddCommand(generateCmd())
|
|
||||||
rootCmd.AddCommand(unsetCmd())
|
|
||||||
rootCmd.AddCommand(rotateCmd())
|
|
||||||
rootCmd.AddCommand(adminInitCmd())
|
|
||||||
rootCmd.AddCommand(setCmd())
|
|
||||||
|
|
||||||
if err := rootCmd.Execute(); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getCmd() *cobra.Command {
|
|
||||||
var showUsername bool
|
|
||||||
cmd := &cobra.Command{
|
|
||||||
Use: "get [key]",
|
|
||||||
Short: "Get password for a key",
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
key := args[0]
|
|
||||||
password, user, err := getPassword(key)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if showUsername {
|
|
||||||
fmt.Println(user)
|
|
||||||
} else {
|
|
||||||
fmt.Println(password)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
cmd.Flags().BoolVar(&showUsername, "username", false, "Show username instead of password")
|
|
||||||
return cmd
|
|
||||||
}
|
|
||||||
|
|
||||||
func generateCmd() *cobra.Command {
|
|
||||||
var user string
|
|
||||||
cmd := &cobra.Command{
|
|
||||||
Use: "generate [key]",
|
|
||||||
Short: "Generate a new password",
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
key := args[0]
|
|
||||||
// Check if agent is trying to set password
|
|
||||||
if os.Getenv("AGENT") != "" || os.Getenv("AGENT_WORKSPACE") != "" {
|
|
||||||
fmt.Fprintln(os.Stderr, "Error: Agents cannot set passwords. Use generate instead.")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
password, err := generatePassword(32)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if err := setPassword(key, user, password); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
fmt.Println(password)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
cmd.Flags().StringVar(&user, "username", "", "Username associated with the password")
|
|
||||||
return cmd
|
|
||||||
}
|
|
||||||
|
|
||||||
func unsetCmd() *cobra.Command {
|
|
||||||
return &cobra.Command{
|
|
||||||
Use: "unset [key]",
|
|
||||||
Short: "Remove a password",
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
key := args[0]
|
|
||||||
if err := removePassword(key); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func rotateCmd() *cobra.Command {
|
|
||||||
return &cobra.Command{
|
|
||||||
Use: "rotate [key]",
|
|
||||||
Short: "Rotate password for a key",
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
key := args[0]
|
|
||||||
// Check if initialized
|
|
||||||
if !isInitialized() {
|
|
||||||
fmt.Fprintln(os.Stderr, "Error: pass_mgr not initialized. Run 'pass_mgr admin init' first.")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get current user if exists
|
|
||||||
_, user, err := getPassword(key)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate new password
|
|
||||||
newPassword, err := generatePassword(32)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := setPassword(key, user, newPassword); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
fmt.Println(newPassword)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func adminInitCmd() *cobra.Command {
|
|
||||||
return &cobra.Command{
|
|
||||||
Use: "admin init",
|
|
||||||
Short: "Initialize pass_mgr with admin key",
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
if err := initAdminInteractive(); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
fmt.Println("pass_mgr initialized successfully")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func setCmd() *cobra.Command {
|
|
||||||
var user string
|
|
||||||
cmd := &cobra.Command{
|
|
||||||
Use: "set [key] [password]",
|
|
||||||
Short: "Set password (admin only)",
|
|
||||||
Args: cobra.ExactArgs(2),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
// Check if agent is trying to set password
|
|
||||||
if os.Getenv("AGENT") != "" || os.Getenv("AGENT_WORKSPACE") != "" {
|
|
||||||
fmt.Fprintln(os.Stderr, "Error: Agents cannot set passwords. Only humans can use 'set'.")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
key := args[0]
|
|
||||||
password := args[1]
|
|
||||||
|
|
||||||
if err := setPassword(key, user, password); err != nil {
|
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
cmd.Flags().StringVar(&user, "username", "", "Username associated with the password")
|
|
||||||
return cmd
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper functions
|
|
||||||
|
|
||||||
func getHomeDir() string {
|
|
||||||
home, err := os.UserHomeDir()
|
|
||||||
if err != nil {
|
|
||||||
return "."
|
|
||||||
}
|
|
||||||
return home
|
|
||||||
}
|
|
||||||
|
|
||||||
func getAdminKeyPath() string {
|
|
||||||
return filepath.Join(getHomeDir(), AdminKeyDir, AdminKeyFile)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getConfigPath() string {
|
|
||||||
return filepath.Join(getHomeDir(), AdminKeyDir, "config.json")
|
|
||||||
}
|
|
||||||
|
|
||||||
func isInitialized() bool {
|
|
||||||
_, err := os.Stat(getConfigPath())
|
|
||||||
return err == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func loadAdminKey() ([]byte, error) {
|
|
||||||
keyPath := getAdminKeyPath()
|
|
||||||
key, err := os.ReadFile(keyPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to load admin key: %w", err)
|
|
||||||
}
|
|
||||||
// Hash the key to get 32 bytes for AES-256
|
|
||||||
hash := sha256.Sum256(key)
|
|
||||||
return hash[:], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func initAdminInteractive() error {
|
|
||||||
fmt.Print("Enter admin password: ")
|
|
||||||
password1, err := term.ReadPassword(int(syscall.Stdin))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to read password: %w", err)
|
|
||||||
}
|
|
||||||
fmt.Println()
|
|
||||||
|
|
||||||
// Trim whitespace/newlines
|
|
||||||
password1 = []byte(strings.TrimSpace(string(password1)))
|
|
||||||
|
|
||||||
// Validate password length
|
|
||||||
if len(password1) < 6 {
|
|
||||||
return fmt.Errorf("password must be at least 6 characters long (got %d)", len(password1))
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Print("Confirm admin password: ")
|
|
||||||
password2, err := term.ReadPassword(int(syscall.Stdin))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to read password confirmation: %w", err)
|
|
||||||
}
|
|
||||||
fmt.Println()
|
|
||||||
|
|
||||||
// Trim whitespace/newlines
|
|
||||||
password2 = []byte(strings.TrimSpace(string(password2)))
|
|
||||||
|
|
||||||
// Check passwords match
|
|
||||||
if string(password1) != string(password2) {
|
|
||||||
return fmt.Errorf("passwords do not match")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save the key
|
|
||||||
return saveAdminKey(password1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func saveAdminKey(key []byte) error {
|
|
||||||
homeDir := getHomeDir()
|
|
||||||
adminDir := filepath.Join(homeDir, AdminKeyDir)
|
|
||||||
|
|
||||||
// Create admin directory
|
|
||||||
if err := os.MkdirAll(adminDir, 0700); err != nil {
|
|
||||||
return fmt.Errorf("failed to create admin directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save key
|
|
||||||
keyFile := filepath.Join(adminDir, AdminKeyFile)
|
|
||||||
if err := os.WriteFile(keyFile, key, 0600); err != nil {
|
|
||||||
return fmt.Errorf("failed to save key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save config
|
|
||||||
config := Config{
|
|
||||||
KeyHash: fmt.Sprintf("%x", sha256.Sum256(key)),
|
|
||||||
Algorithm: DefaultAlgorithm,
|
|
||||||
}
|
|
||||||
configData, _ := json.MarshalIndent(config, "", " ")
|
|
||||||
configPath := filepath.Join(adminDir, "config.json")
|
|
||||||
if err := os.WriteFile(configPath, configData, 0600); err != nil {
|
|
||||||
return fmt.Errorf("failed to save config: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func initAdmin(keyPath string) error {
|
|
||||||
// Read provided key
|
|
||||||
key, err := os.ReadFile(keyPath)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to read key file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate password length (must be >= 6 characters)
|
|
||||||
if len(key) < 6 {
|
|
||||||
return fmt.Errorf("password must be at least 6 characters long (got %d)", len(key))
|
|
||||||
}
|
|
||||||
|
|
||||||
return saveAdminKey(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func getSecretsDir() string {
|
|
||||||
if workspaceDir != "" && agentID != "" {
|
|
||||||
return filepath.Join(workspaceDir, SecretsDirName, agentID)
|
|
||||||
}
|
|
||||||
// Fallback to home directory
|
|
||||||
return filepath.Join(getHomeDir(), SecretsDirName, "default")
|
|
||||||
}
|
|
||||||
|
|
||||||
func getPasswordFilePath(key string) string {
|
|
||||||
return filepath.Join(getSecretsDir(), key+".gpg")
|
|
||||||
}
|
|
||||||
|
|
||||||
func encrypt(plaintext []byte, key []byte) (*EncryptedData, error) {
|
|
||||||
block, err := aes.NewCipher(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
gcm, err := cipher.NewGCM(block)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
nonce := make([]byte, gcm.NonceSize())
|
|
||||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
|
|
||||||
|
|
||||||
return &EncryptedData{
|
|
||||||
Algorithm: DefaultAlgorithm,
|
|
||||||
Nonce: base64.StdEncoding.EncodeToString(nonce),
|
|
||||||
Data: base64.StdEncoding.EncodeToString(ciphertext[gcm.NonceSize():]),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func decrypt(data *EncryptedData, key []byte) ([]byte, error) {
|
|
||||||
ciphertext, err := base64.StdEncoding.DecodeString(data.Data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
nonce, err := base64.StdEncoding.DecodeString(data.Nonce)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
block, err := aes.NewCipher(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
gcm, err := cipher.NewGCM(block)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return plaintext, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func setPassword(key, user, password string) error {
|
|
||||||
if !isInitialized() {
|
|
||||||
return fmt.Errorf("pass_mgr not initialized. Run 'pass_mgr admin init' first")
|
|
||||||
}
|
|
||||||
|
|
||||||
adminKey, err := loadAdminKey()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create secrets directory
|
|
||||||
secretsDir := getSecretsDir()
|
|
||||||
if err := os.MkdirAll(secretsDir, 0700); err != nil {
|
|
||||||
return fmt.Errorf("failed to create secrets directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encrypt password
|
|
||||||
data := map[string]string{
|
|
||||||
"password": password,
|
|
||||||
"user": user,
|
|
||||||
}
|
|
||||||
plaintext, _ := json.Marshal(data)
|
|
||||||
|
|
||||||
encrypted, err := encrypt(plaintext, adminKey)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to encrypt: %w", err)
|
|
||||||
}
|
|
||||||
encrypted.User = user
|
|
||||||
|
|
||||||
// Save to file
|
|
||||||
filePath := getPasswordFilePath(key)
|
|
||||||
fileData, _ := json.MarshalIndent(encrypted, "", " ")
|
|
||||||
if err := os.WriteFile(filePath, fileData, 0600); err != nil {
|
|
||||||
return fmt.Errorf("failed to save password: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getPassword(key string) (string, string, error) {
|
|
||||||
if !isInitialized() {
|
|
||||||
return "", "", fmt.Errorf("pass_mgr not initialized. Run 'pass_mgr admin init' first")
|
|
||||||
}
|
|
||||||
|
|
||||||
adminKey, err := loadAdminKey()
|
|
||||||
if err != nil {
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
filePath := getPasswordFilePath(key)
|
|
||||||
fileData, err := os.ReadFile(filePath)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", fmt.Errorf("password not found: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var encrypted EncryptedData
|
|
||||||
if err := json.Unmarshal(fileData, &encrypted); err != nil {
|
|
||||||
return "", "", fmt.Errorf("failed to parse password file: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
plaintext, err := decrypt(&encrypted, adminKey)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", fmt.Errorf("failed to decrypt: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var data map[string]string
|
|
||||||
if err := json.Unmarshal(plaintext, &data); err != nil {
|
|
||||||
return "", "", fmt.Errorf("failed to parse decrypted data: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return data["password"], data["user"], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func removePassword(key string) error {
|
|
||||||
if !isInitialized() {
|
|
||||||
return fmt.Errorf("pass_mgr not initialized. Run 'pass_mgr admin init' first")
|
|
||||||
}
|
|
||||||
|
|
||||||
filePath := getPasswordFilePath(key)
|
|
||||||
if err := os.Remove(filePath); err != nil {
|
|
||||||
return fmt.Errorf("failed to remove password: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func generatePassword(length int) (string, error) {
|
|
||||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*"
|
|
||||||
password := make([]byte, length)
|
|
||||||
for i := range password {
|
|
||||||
randomByte := make([]byte, 1)
|
|
||||||
if _, err := rand.Read(randomByte); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
password[i] = charset[int(randomByte[0])%len(charset)]
|
|
||||||
}
|
|
||||||
return string(password), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckForAdminLeak checks if admin password appears in message/tool calling
|
|
||||||
func CheckForAdminLeak(content string) bool {
|
|
||||||
// This is a placeholder - actual implementation should check against actual admin password
|
|
||||||
// This function should be called by the plugin to monitor messages
|
|
||||||
configPath := getConfigPath()
|
|
||||||
if _, err := os.Stat(configPath); err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Implement actual leak detection
|
|
||||||
// For now, just check if content contains common patterns
|
|
||||||
return strings.Contains(content, "admin") && strings.Contains(content, "password")
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResetOnLeak resets pass_mgr to uninitialized state and logs security breach
|
|
||||||
func ResetOnLeak() error {
|
|
||||||
configPath := getConfigPath()
|
|
||||||
|
|
||||||
// Remove config (but keep key file for potential recovery)
|
|
||||||
if err := os.Remove(configPath); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Log security breach
|
|
||||||
logPath := filepath.Join(getHomeDir(), AdminKeyDir, "security_breach.log")
|
|
||||||
logEntry := fmt.Sprintf("[%s] CRITICAL: Admin password leaked! pass_mgr reset to uninitialized state.\n",
|
|
||||||
time.Now().Format(time.RFC3339))
|
|
||||||
|
|
||||||
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
if _, err := f.WriteString(logEntry); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
3846
pcexec/package-lock.json
generated
3846
pcexec/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,21 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "pcexec",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"description": "Safe exec wrapper for OpenClaw with password sanitization",
|
|
||||||
"main": "dist/index.js",
|
|
||||||
"types": "dist/index.d.ts",
|
|
||||||
"scripts": {
|
|
||||||
"build": "tsc",
|
|
||||||
"dev": "tsc --watch",
|
|
||||||
"test": "jest"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@types/node": "^20.0.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"typescript": "^5.0.0",
|
|
||||||
"jest": "^29.0.0",
|
|
||||||
"@types/jest": "^29.0.0",
|
|
||||||
"ts-jest": "^29.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,366 +0,0 @@
|
|||||||
import { spawn, SpawnOptions } from 'child_process';
|
|
||||||
import { promisify } from 'util';
|
|
||||||
|
|
||||||
const execAsync = promisify(require('child_process').exec);
|
|
||||||
|
|
||||||
export interface PcExecOptions {
|
|
||||||
/** Current working directory */
|
|
||||||
cwd?: string;
|
|
||||||
/** Environment variables */
|
|
||||||
env?: Record<string, string>;
|
|
||||||
/** Timeout in milliseconds */
|
|
||||||
timeout?: number;
|
|
||||||
/** Maximum buffer size for stdout/stderr */
|
|
||||||
maxBuffer?: number;
|
|
||||||
/** Kill signal */
|
|
||||||
killSignal?: NodeJS.Signals;
|
|
||||||
/** Shell to use */
|
|
||||||
shell?: string | boolean;
|
|
||||||
/** UID to run as */
|
|
||||||
uid?: number;
|
|
||||||
/** GID to run as */
|
|
||||||
gid?: number;
|
|
||||||
/** Window style (Windows only) */
|
|
||||||
windowsHide?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PcExecResult {
|
|
||||||
/** Standard output */
|
|
||||||
stdout: string;
|
|
||||||
/** Standard error */
|
|
||||||
stderr: string;
|
|
||||||
/** Exit code */
|
|
||||||
exitCode: number;
|
|
||||||
/** Command that was executed */
|
|
||||||
command: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PcExecError extends Error {
|
|
||||||
/** Exit code */
|
|
||||||
code?: number;
|
|
||||||
/** Signal that terminated the process */
|
|
||||||
signal?: string;
|
|
||||||
/** Standard output */
|
|
||||||
stdout: string;
|
|
||||||
/** Standard error */
|
|
||||||
stderr: string;
|
|
||||||
/** Killed by timeout */
|
|
||||||
killed?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extract pass_mgr get commands from a command string
|
|
||||||
* Supports formats like:
|
|
||||||
* - $(pass_mgr get key)
|
|
||||||
* - `pass_mgr get key`
|
|
||||||
* - pass_mgr get key (direct invocation)
|
|
||||||
*/
|
|
||||||
function extractPassMgrGets(command: string): Array<{ key: string; fullMatch: string }> {
|
|
||||||
const results: Array<{ key: string; fullMatch: string }> = [];
|
|
||||||
|
|
||||||
// Pattern for $(pass_mgr get key) or `pass_mgr get key`
|
|
||||||
const patterns = [
|
|
||||||
/\$\(\s*pass_mgr\s+get\s+(\S+)\s*\)/g,
|
|
||||||
/`\s*pass_mgr\s+get\s+(\S+)\s*`/g,
|
|
||||||
/pass_mgr\s+get\s+(\S+)/g,
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const pattern of patterns) {
|
|
||||||
let match;
|
|
||||||
while ((match = pattern.exec(command)) !== null) {
|
|
||||||
results.push({
|
|
||||||
key: match[1],
|
|
||||||
fullMatch: match[0],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return results;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute pass_mgr get and return the password
|
|
||||||
*/
|
|
||||||
async function getPassword(key: string): Promise<string> {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const passMgrPath = process.env.PASS_MGR_PATH || 'pass_mgr';
|
|
||||||
const child = spawn(passMgrPath, ['get', key], {
|
|
||||||
stdio: ['ignore', 'pipe', 'pipe'],
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
AGENT_WORKSPACE: process.env.AGENT_WORKSPACE || '',
|
|
||||||
AGENT_ID: process.env.AGENT_ID || '',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
let stdout = '';
|
|
||||||
let stderr = '';
|
|
||||||
|
|
||||||
child.stdout.on('data', (data) => {
|
|
||||||
stdout += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
child.stderr.on('data', (data) => {
|
|
||||||
stderr += data.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
child.on('close', (code) => {
|
|
||||||
if (code !== 0) {
|
|
||||||
reject(new Error(`pass_mgr get failed: ${stderr || stdout}`));
|
|
||||||
} else {
|
|
||||||
resolve(stdout.trim());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
child.on('error', (err) => {
|
|
||||||
reject(err);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sanitize output by replacing passwords with ######
|
|
||||||
*/
|
|
||||||
function sanitizeOutput(output: string, passwords: string[]): string {
|
|
||||||
let sanitized = output;
|
|
||||||
for (const password of passwords) {
|
|
||||||
if (password) {
|
|
||||||
// Escape special regex characters
|
|
||||||
const escaped = password.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
||||||
const regex = new RegExp(escaped, 'g');
|
|
||||||
sanitized = sanitized.replace(regex, '######');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return sanitized;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Replace pass_mgr get commands with actual passwords in command
|
|
||||||
*/
|
|
||||||
async function replacePassMgrGets(command: string): Promise<{ command: string; passwords: string[] }> {
|
|
||||||
const passMgrGets = extractPassMgrGets(command);
|
|
||||||
const passwords: string[] = [];
|
|
||||||
let replacedCommand = command;
|
|
||||||
|
|
||||||
for (const { key, fullMatch } of passMgrGets) {
|
|
||||||
try {
|
|
||||||
const password = await getPassword(key);
|
|
||||||
passwords.push(password);
|
|
||||||
replacedCommand = replacedCommand.replace(fullMatch, password);
|
|
||||||
} catch (err) {
|
|
||||||
throw new Error(`Failed to get password for key '${key}': ${err}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { command: replacedCommand, passwords };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Safe exec wrapper that handles pass_mgr get commands and sanitizes output
|
|
||||||
*
|
|
||||||
* @param command - Command to execute
|
|
||||||
* @param options - Execution options
|
|
||||||
* @returns Promise resolving to execution result
|
|
||||||
*/
|
|
||||||
export async function pcexec(command: string, options: PcExecOptions = {}): Promise<PcExecResult> {
|
|
||||||
// Set up environment with workspace/agent info
|
|
||||||
const env: Record<string, string> = {};
|
|
||||||
|
|
||||||
// Copy process.env, filtering out undefined values
|
|
||||||
for (const [key, value] of Object.entries(process.env)) {
|
|
||||||
if (value !== undefined) {
|
|
||||||
env[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge options.env
|
|
||||||
if (options.env) {
|
|
||||||
Object.assign(env, options.env);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.env.AGENT_WORKSPACE) {
|
|
||||||
env.AGENT_WORKSPACE = process.env.AGENT_WORKSPACE;
|
|
||||||
}
|
|
||||||
if (process.env.AGENT_ID) {
|
|
||||||
env.AGENT_ID = process.env.AGENT_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract and replace pass_mgr get commands
|
|
||||||
let finalCommand = command;
|
|
||||||
let passwords: string[] = [];
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await replacePassMgrGets(command);
|
|
||||||
finalCommand = result.command;
|
|
||||||
passwords = result.passwords;
|
|
||||||
} catch (err) {
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const spawnOptions: SpawnOptions = {
|
|
||||||
cwd: options.cwd,
|
|
||||||
env,
|
|
||||||
// Don't use shell by default - we're already using bash -c explicitly
|
|
||||||
shell: options.shell,
|
|
||||||
windowsHide: options.windowsHide,
|
|
||||||
uid: options.uid,
|
|
||||||
gid: options.gid,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Use bash for better compatibility
|
|
||||||
const child = spawn('bash', ['-c', finalCommand], spawnOptions);
|
|
||||||
|
|
||||||
let stdout = '';
|
|
||||||
let stderr = '';
|
|
||||||
let killed = false;
|
|
||||||
let timeoutId: NodeJS.Timeout | null = null;
|
|
||||||
|
|
||||||
// Set up timeout
|
|
||||||
if (options.timeout && options.timeout > 0) {
|
|
||||||
timeoutId = setTimeout(() => {
|
|
||||||
killed = true;
|
|
||||||
child.kill(options.killSignal || 'SIGTERM');
|
|
||||||
}, options.timeout);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle stdout
|
|
||||||
child.stdout?.on('data', (data) => {
|
|
||||||
stdout += data.toString();
|
|
||||||
|
|
||||||
// Check maxBuffer
|
|
||||||
if (options.maxBuffer && stdout.length > options.maxBuffer) {
|
|
||||||
child.kill(options.killSignal || 'SIGTERM');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle stderr
|
|
||||||
child.stderr?.on('data', (data) => {
|
|
||||||
stderr += data.toString();
|
|
||||||
|
|
||||||
// Check maxBuffer
|
|
||||||
if (options.maxBuffer && stderr.length > options.maxBuffer) {
|
|
||||||
child.kill(options.killSignal || 'SIGTERM');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle process close
|
|
||||||
child.on('close', (code, signal) => {
|
|
||||||
if (timeoutId) {
|
|
||||||
clearTimeout(timeoutId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanitize output
|
|
||||||
const sanitizedStdout = sanitizeOutput(stdout, passwords);
|
|
||||||
const sanitizedStderr = sanitizeOutput(stderr, passwords);
|
|
||||||
|
|
||||||
if (code === 0) {
|
|
||||||
resolve({
|
|
||||||
stdout: sanitizedStdout,
|
|
||||||
stderr: sanitizedStderr,
|
|
||||||
exitCode: 0,
|
|
||||||
command: finalCommand,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
const error = new Error(`Command failed: ${command}`) as PcExecError;
|
|
||||||
error.code = code ?? undefined;
|
|
||||||
error.signal = signal ?? undefined;
|
|
||||||
error.stdout = sanitizedStdout;
|
|
||||||
error.stderr = sanitizedStderr;
|
|
||||||
error.killed = killed;
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle process error
|
|
||||||
child.on('error', (err) => {
|
|
||||||
if (timeoutId) {
|
|
||||||
clearTimeout(timeoutId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const error = new Error(`Failed to execute command: ${err.message}`) as PcExecError;
|
|
||||||
error.stdout = sanitizeOutput(stdout, passwords);
|
|
||||||
error.stderr = sanitizeOutput(stderr, passwords);
|
|
||||||
reject(error);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Synchronous version of pcexec
|
|
||||||
* Note: Password sanitization is still applied
|
|
||||||
*/
|
|
||||||
export function pcexecSync(command: string, options: PcExecOptions = {}): PcExecResult {
|
|
||||||
const { execSync } = require('child_process');
|
|
||||||
|
|
||||||
// Set up environment
|
|
||||||
const env: Record<string, string> = {};
|
|
||||||
|
|
||||||
// Copy process.env, filtering out undefined values
|
|
||||||
for (const [key, value] of Object.entries(process.env)) {
|
|
||||||
if (value !== undefined) {
|
|
||||||
env[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge options.env
|
|
||||||
if (options.env) {
|
|
||||||
Object.assign(env, options.env);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.env.AGENT_WORKSPACE) {
|
|
||||||
env.AGENT_WORKSPACE = process.env.AGENT_WORKSPACE;
|
|
||||||
}
|
|
||||||
if (process.env.AGENT_ID) {
|
|
||||||
env.AGENT_ID = process.env.AGENT_ID;
|
|
||||||
}
|
|
||||||
|
|
||||||
// For sync version, we need to pre-resolve passwords
|
|
||||||
// This is a limitation - passwords will be in command
|
|
||||||
const passMgrGets = extractPassMgrGets(command);
|
|
||||||
let finalCommand = command;
|
|
||||||
const passwords: string[] = [];
|
|
||||||
|
|
||||||
// Note: In sync version, we can't async fetch passwords
|
|
||||||
// So we use the original command and rely on the user to not use pass_mgr gets in sync mode
|
|
||||||
// Or they need to resolve passwords beforehand
|
|
||||||
|
|
||||||
const execOptions: any = {
|
|
||||||
cwd: options.cwd,
|
|
||||||
env,
|
|
||||||
// Don't use shell by default
|
|
||||||
shell: options.shell,
|
|
||||||
encoding: 'utf8',
|
|
||||||
windowsHide: options.windowsHide,
|
|
||||||
uid: options.uid,
|
|
||||||
gid: options.gid,
|
|
||||||
maxBuffer: options.maxBuffer,
|
|
||||||
timeout: options.timeout,
|
|
||||||
killSignal: options.killSignal,
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const stdout = execSync(finalCommand, execOptions);
|
|
||||||
const sanitizedStdout = sanitizeOutput(stdout.toString(), passwords);
|
|
||||||
|
|
||||||
return {
|
|
||||||
stdout: sanitizedStdout,
|
|
||||||
stderr: '',
|
|
||||||
exitCode: 0,
|
|
||||||
command: finalCommand,
|
|
||||||
};
|
|
||||||
} catch (err: any) {
|
|
||||||
const sanitizedStdout = sanitizeOutput(err.stdout?.toString() || '', passwords);
|
|
||||||
const sanitizedStderr = sanitizeOutput(err.stderr?.toString() || '', passwords);
|
|
||||||
|
|
||||||
const error = new Error(`Command failed: ${command}`) as PcExecError;
|
|
||||||
error.code = err.status;
|
|
||||||
error.signal = err.signal;
|
|
||||||
error.stdout = sanitizedStdout;
|
|
||||||
error.stderr = sanitizedStderr;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default export
|
|
||||||
export default pcexec;
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2020",
|
|
||||||
"module": "commonjs",
|
|
||||||
"lib": ["ES2020"],
|
|
||||||
"outDir": "./dist",
|
|
||||||
"rootDir": "./src",
|
|
||||||
"strict": true,
|
|
||||||
"esModuleInterop": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"forceConsistentCasingInFileNames": true,
|
|
||||||
"declaration": true,
|
|
||||||
"declarationMap": true,
|
|
||||||
"sourceMap": true,
|
|
||||||
"resolveJsonModule": true
|
|
||||||
},
|
|
||||||
"include": ["src/**/*"],
|
|
||||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
|
||||||
}
|
|
||||||
3
pcguard/go.mod
Normal file
3
pcguard/go.mod
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module pcguard
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
36
pcguard/src/main.go
Normal file
36
pcguard/src/main.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Must match the sentinel value injected by pcexec
|
||||||
|
expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"
|
||||||
|
errorMessage = "PLEASE USE TOOL PCEXEC TO RUN THIS SCRIPT"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
agentVerify := os.Getenv("AGENT_VERIFY")
|
||||||
|
agentID := os.Getenv("AGENT_ID")
|
||||||
|
agentWorkspace := os.Getenv("AGENT_WORKSPACE")
|
||||||
|
|
||||||
|
if agentVerify != expectedAgentVerify {
|
||||||
|
fmt.Fprintln(os.Stderr, errorMessage)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if agentID == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, errorMessage)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if agentWorkspace == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, errorMessage)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// All checks passed — output nothing, exit 0
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
83
plans/PROXY_PC_EXEC.md
Normal file
83
plans/PROXY_PC_EXEC.md
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
# PROXY_PC_EXEC
|
||||||
|
|
||||||
|
## 背景
|
||||||
|
新增一个可代理执行的安全命令工具,整体行为尽量保持与现有 `pcexec` 一致,但允许在受控条件下以指定的代理身份注入 `AGENT_ID`。
|
||||||
|
|
||||||
|
## 开发想法整理
|
||||||
|
|
||||||
|
### 1. 新建工具 `proxy-pcexec`
|
||||||
|
- 新增一个工具:`proxy-pcexec`
|
||||||
|
- 目标是复用或对齐现有 `pcexec` 的能力与行为
|
||||||
|
- 预期执行语义与安全边界尽量和 `pcexec` 保持一致,避免出现两套不同标准
|
||||||
|
|
||||||
|
### 2. 扩展 `openclaw.plugin.json`
|
||||||
|
需要在 `openclaw.plugin.json` 中新增配置字段:
|
||||||
|
- `config.proxyAllowlist`
|
||||||
|
|
||||||
|
兼容性说明:
|
||||||
|
- 如有需要,也可兼容读取 `proxy-allowlist` 作为别名
|
||||||
|
|
||||||
|
用途:
|
||||||
|
- 用于声明哪些 agent 允许调用 `proxy-pcexec`
|
||||||
|
- 只有在该 allowlist 中的 agent,才具备调用该工具的权限
|
||||||
|
|
||||||
|
建议约束:
|
||||||
|
- `config.proxyAllowlist` 应为 agent 标识列表
|
||||||
|
- `allowlist` 仅支持精确匹配,不支持通配、分组或模糊匹配
|
||||||
|
- 若调用方不在 allowlist 中,应直接拒绝调用
|
||||||
|
- 默认配置应偏保守;未配置时建议视为不允许任何 agent 调用
|
||||||
|
- 一旦调用方 agent 在 allowlist 中,则允许其代理任意 `proxy-for` 值
|
||||||
|
|
||||||
|
### 3. `proxy-pcexec` 与 `pcexec` 的关键区别
|
||||||
|
`proxy-pcexec` 的功能与 `pcexec` 基本一致,核心差异如下:
|
||||||
|
|
||||||
|
#### `pcexec`
|
||||||
|
- 直接将调用者的 `agent-id` 注入环境变量 `AGENT_ID`
|
||||||
|
|
||||||
|
#### `proxy-pcexec`
|
||||||
|
- 不直接使用调用者的 `agent-id` 作为 `AGENT_ID`
|
||||||
|
- 增加一个**必填**工具参数:`proxy-for`
|
||||||
|
- 实际注入到环境变量 `AGENT_ID` 中的值,取自 `proxy-for`
|
||||||
|
|
||||||
|
## 建议的行为规则
|
||||||
|
|
||||||
|
### 调用参数
|
||||||
|
`proxy-pcexec` 至少包含:
|
||||||
|
- `command`
|
||||||
|
- `proxy-for`(必填)
|
||||||
|
- 其他参数可尽量与 `pcexec` 保持一致
|
||||||
|
|
||||||
|
### 权限校验
|
||||||
|
调用 `proxy-pcexec` 时应至少进行以下校验:
|
||||||
|
1. 校验调用方 agent 是否在 `config.proxyAllowlist` 中(精确匹配)
|
||||||
|
2. 校验 `proxy-for` 是否存在且非空
|
||||||
|
3. 不要求 `proxy-for` 必须是已注册或已知 agent-id,可自由填写
|
||||||
|
4. 通过校验后,再执行与 `pcexec` 等价的命令执行流程
|
||||||
|
|
||||||
|
说明:
|
||||||
|
- allowlist 控制的是“谁可以发起代理执行”
|
||||||
|
- 只要调用方 agent 在 allowlist 中,就允许其代理任意 agent
|
||||||
|
|
||||||
|
### 环境变量注入
|
||||||
|
- `AGENT_ID` = `proxy-for`
|
||||||
|
- `PROXY_PCEXEC_EXECUTOR` = 调用方真实 `agent-id`
|
||||||
|
- `PCEXEC_PROXIED` = `true`
|
||||||
|
- 不应再把原始调用者的 `agent-id` 直接写入 `AGENT_ID`
|
||||||
|
|
||||||
|
## 设计目标
|
||||||
|
- 保持与 `pcexec` 尽可能一致,降低维护成本
|
||||||
|
- 通过 allowlist 控制谁可以发起代理执行
|
||||||
|
- 通过显式 `proxy-for` 参数,避免隐式身份继承
|
||||||
|
- 让代理身份切换是显式、可审计、可配置的
|
||||||
|
|
||||||
|
## 日志与审计
|
||||||
|
建议日志至少记录:
|
||||||
|
- `executor`(调用方真实 agent-id)
|
||||||
|
- `proxy-for`
|
||||||
|
- 最终执行命令
|
||||||
|
|
||||||
|
## 已明确的设计结论
|
||||||
|
- `proxy-for` 可以随意填写,不要求必须是已注册 agent
|
||||||
|
- 日志需要记录 `executor` 和 `proxy-for`
|
||||||
|
- `config.proxyAllowlist` 仅支持精确匹配
|
||||||
|
- allowlist 中的 agent 可以代理任意 agent,不需要额外的 `proxy-for` 限制
|
||||||
214
plugin/commands/ego-mgr-slash.ts
Normal file
214
plugin/commands/ego-mgr-slash.ts
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
import { pcexec } from '../tools/pcexec';
|
||||||
|
|
||||||
|
export interface EgoMgrSlashCommandOptions {
|
||||||
|
/** OpenClaw base path */
|
||||||
|
openclawPath: string;
|
||||||
|
/** Current agent ID */
|
||||||
|
agentId: string;
|
||||||
|
/** Current workspace directory */
|
||||||
|
workspaceDir: string;
|
||||||
|
/** Callback for replies */
|
||||||
|
onReply: (message: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sentinel value injected into every pcexec subprocess */
|
||||||
|
const AGENT_VERIFY = 'IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE';
|
||||||
|
|
||||||
|
export class EgoMgrSlashCommand {
|
||||||
|
private openclawPath: string;
|
||||||
|
private agentId: string;
|
||||||
|
private workspaceDir: string;
|
||||||
|
private onReply: (message: string) => Promise<void>;
|
||||||
|
private binDir: string;
|
||||||
|
|
||||||
|
constructor(options: EgoMgrSlashCommandOptions) {
|
||||||
|
this.openclawPath = options.openclawPath;
|
||||||
|
this.agentId = options.agentId;
|
||||||
|
this.workspaceDir = options.workspaceDir;
|
||||||
|
this.onReply = options.onReply;
|
||||||
|
this.binDir = require('path').join(this.openclawPath, 'bin');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle /ego-mgr slash command
|
||||||
|
* @param command Full command string (e.g., "/ego-mgr get name")
|
||||||
|
*/
|
||||||
|
async handle(command: string): Promise<void> {
|
||||||
|
const parts = command.trim().split(/\s+/);
|
||||||
|
// Remove the "/ego-mgr" prefix
|
||||||
|
const args = parts.slice(1);
|
||||||
|
const subcommand = args[0];
|
||||||
|
|
||||||
|
if (!subcommand) {
|
||||||
|
await this.showUsage();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
switch (subcommand) {
|
||||||
|
case 'get':
|
||||||
|
await this.handleGet(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'set':
|
||||||
|
await this.handleSet(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'list':
|
||||||
|
await this.handleList(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'delete':
|
||||||
|
await this.handleDelete(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'add-column':
|
||||||
|
await this.handleAddColumn(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'add-public-column':
|
||||||
|
await this.handleAddPublicColumn(args.slice(1));
|
||||||
|
break;
|
||||||
|
case 'show':
|
||||||
|
await this.handleShow();
|
||||||
|
break;
|
||||||
|
case 'help':
|
||||||
|
default:
|
||||||
|
await this.showUsage();
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
await this.onReply(`Error: ${error.message || error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async showUsage(): Promise<void> {
|
||||||
|
const usage = [
|
||||||
|
'**ego-mgr Commands**',
|
||||||
|
'',
|
||||||
|
'`/ego-mgr get <column-name>` - Get field value',
|
||||||
|
'`/ego-mgr set <column-name> <value>` - Set field value',
|
||||||
|
'`/ego-mgr list` - List all field names',
|
||||||
|
'`/ego-mgr delete <column-name>` - Delete a field',
|
||||||
|
'`/ego-mgr add-column <column-name>` - Add an Agent Scope field',
|
||||||
|
'`/ego-mgr add-public-column <column-name>` - Add a Public Scope field',
|
||||||
|
'`/ego-mgr show` - Show all fields and values',
|
||||||
|
'',
|
||||||
|
'Examples:',
|
||||||
|
'`/ego-mgr get name`',
|
||||||
|
'`/ego-mgr set timezone Asia/Shanghai`',
|
||||||
|
].join('\n');
|
||||||
|
await this.onReply(usage);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleGet(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr get <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
const result = await this.execEgoMgr(['get', columnName]);
|
||||||
|
await this.onReply(`**${columnName}**: ${result || '(empty)'}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleSet(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 2) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr set <column-name> <value>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
const value = args.slice(1).join(' '); // Support values with spaces
|
||||||
|
await this.execEgoMgr(['set', columnName, value]);
|
||||||
|
await this.onReply(`Set **${columnName}** = \`${value}\``);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleList(args: string[]): Promise<void> {
|
||||||
|
const result = await this.execEgoMgr(['list', 'columns']);
|
||||||
|
if (!result.trim()) {
|
||||||
|
await this.onReply('No fields defined');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columns = result.split('\n').filter(Boolean);
|
||||||
|
const lines = ['**Fields**:', ''];
|
||||||
|
for (const col of columns) {
|
||||||
|
lines.push(`• ${col}`);
|
||||||
|
}
|
||||||
|
await this.onReply(lines.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleDelete(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr delete <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
await this.execEgoMgr(['delete', columnName]);
|
||||||
|
await this.onReply(`Deleted field **${columnName}**`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleAddColumn(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr add-column <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
await this.execEgoMgr(['add', 'column', columnName]);
|
||||||
|
await this.onReply(`Added Agent Scope field **${columnName}**`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleAddPublicColumn(args: string[]): Promise<void> {
|
||||||
|
if (args.length < 1) {
|
||||||
|
await this.onReply('Usage: `/ego-mgr add-public-column <column-name>`');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const columnName = args[0];
|
||||||
|
await this.execEgoMgr(['add', 'public-column', columnName]);
|
||||||
|
await this.onReply(`Added Public Scope field **${columnName}**`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleShow(): Promise<void> {
|
||||||
|
const result = await this.execEgoMgr(['show']);
|
||||||
|
if (!result.trim()) {
|
||||||
|
await this.onReply('No field data');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const lines = ['**Field Data**:', ''];
|
||||||
|
lines.push('```');
|
||||||
|
lines.push(result);
|
||||||
|
lines.push('```');
|
||||||
|
await this.onReply(lines.join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute ego-mgr binary via pc-exec
|
||||||
|
*/
|
||||||
|
private async execEgoMgr(args: string[]): Promise<string> {
|
||||||
|
const currentPath = process.env.PATH || '';
|
||||||
|
const newPath = currentPath.includes(this.binDir)
|
||||||
|
? currentPath
|
||||||
|
: `${currentPath}:${this.binDir}`;
|
||||||
|
|
||||||
|
const command = `ego-mgr ${args.map(a => this.shellEscape(a)).join(' ')}`;
|
||||||
|
|
||||||
|
const result = await pcexec(command, {
|
||||||
|
cwd: this.workspaceDir,
|
||||||
|
env: {
|
||||||
|
AGENT_ID: this.agentId,
|
||||||
|
AGENT_WORKSPACE: this.workspaceDir,
|
||||||
|
AGENT_VERIFY,
|
||||||
|
PATH: newPath,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.exitCode !== 0 && result.stderr) {
|
||||||
|
throw new Error(result.stderr);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.stdout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Escape a string for shell usage
|
||||||
|
*/
|
||||||
|
private shellEscape(str: string): string {
|
||||||
|
// Simple escaping for common cases
|
||||||
|
if (/^[a-zA-Z0-9._-]+$/.test(str)) {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
return `'${str.replace(/'/g, "'\"'\"'")}'`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { StatusManager } from './status-manager';
|
import { StatusManager } from '../core/status-manager';
|
||||||
|
|
||||||
export interface SlashCommandOptions {
|
export interface SlashCommandOptions {
|
||||||
statusManager: StatusManager;
|
statusManager: StatusManager;
|
||||||
@@ -48,7 +48,7 @@ export class SlashCommandHandler {
|
|||||||
async handle(command: string, userId: string): Promise<void> {
|
async handle(command: string, userId: string): Promise<void> {
|
||||||
// Check authorization
|
// Check authorization
|
||||||
if (!this.authorizedUsers.includes(userId)) {
|
if (!this.authorizedUsers.includes(userId)) {
|
||||||
await this.onReply('❌ 无权执行此命令');
|
await this.onReply('Unauthorized');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,10 +68,10 @@ export class SlashCommandHandler {
|
|||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
await this.onReply(
|
await this.onReply(
|
||||||
'用法:\n' +
|
'Usage:\n' +
|
||||||
'`/padded-cell-ctrl status` - 查看状态\n' +
|
'`/padded-cell-ctrl status` - Show status\n' +
|
||||||
'`/padded-cell-ctrl enable pass-mgr|safe-restart` - 启用功能\n' +
|
'`/padded-cell-ctrl enable pass-mgr|safe-restart` - Enable feature\n' +
|
||||||
'`/padded-cell-ctrl disable pass-mgr|safe-restart` - 禁用功能'
|
'`/padded-cell-ctrl disable pass-mgr|safe-restart` - Disable feature'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,12 +81,12 @@ export class SlashCommandHandler {
|
|||||||
const agents = this.statusManager.getAllAgents();
|
const agents = this.statusManager.getAllAgents();
|
||||||
|
|
||||||
const lines = [
|
const lines = [
|
||||||
'**PaddedCell 状态**',
|
'**PaddedCell Status**',
|
||||||
'',
|
'',
|
||||||
`🔐 密码管理: ${this.state.passMgrEnabled ? '✅ 启用' : '❌ 禁用'}`,
|
`Secret Manager: ${this.state.passMgrEnabled ? 'Enabled' : 'Disabled'}`,
|
||||||
`🔄 安全重启: ${this.state.safeRestartEnabled ? '✅ 启用' : '❌ 禁用'}`,
|
`Safe Restart: ${this.state.safeRestartEnabled ? 'Enabled' : 'Disabled'}`,
|
||||||
'',
|
'',
|
||||||
'**Agent 状态:**',
|
'**Agent Status:**',
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const agent of agents) {
|
for (const agent of agents) {
|
||||||
@@ -95,14 +95,14 @@ export class SlashCommandHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (agents.length === 0) {
|
if (agents.length === 0) {
|
||||||
lines.push('(暂无 agent 注册)');
|
lines.push('(No agents registered)');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (global.restartStatus !== 'idle') {
|
if (global.restartStatus !== 'idle') {
|
||||||
lines.push('');
|
lines.push('');
|
||||||
lines.push(`⚠️ 重启状态: ${global.restartStatus}`);
|
lines.push(`Restart Status: ${global.restartStatus}`);
|
||||||
if (global.restartScheduledBy) {
|
if (global.restartScheduledBy) {
|
||||||
lines.push(` 由 ${global.restartScheduledBy} 发起`);
|
lines.push(` Initiated by ${global.restartScheduledBy}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,12 +111,12 @@ export class SlashCommandHandler {
|
|||||||
|
|
||||||
private async handleEnable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
private async handleEnable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
||||||
if (!this.isValidFeature(feature)) {
|
if (!this.isValidFeature(feature)) {
|
||||||
await this.onReply('❌ 未知功能。可用选项: pass-mgr, safe-restart');
|
await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.isOnCooldown(feature)) {
|
if (this.isOnCooldown(feature)) {
|
||||||
await this.onReply('⏳ 该功能最近刚被修改过,请稍后再试');
|
await this.onReply('This feature was recently modified. Please try again later.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,17 +127,17 @@ export class SlashCommandHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.state.lastToggle[feature] = Date.now();
|
this.state.lastToggle[feature] = Date.now();
|
||||||
await this.onReply(`✅ 已启用 ${feature}`);
|
await this.onReply(`Enabled ${feature}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleDisable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
private async handleDisable(feature: 'pass-mgr' | 'safe-restart'): Promise<void> {
|
||||||
if (!this.isValidFeature(feature)) {
|
if (!this.isValidFeature(feature)) {
|
||||||
await this.onReply('❌ 未知功能。可用选项: pass-mgr, safe-restart');
|
await this.onReply('Unknown feature. Available: pass-mgr, safe-restart');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.isOnCooldown(feature)) {
|
if (this.isOnCooldown(feature)) {
|
||||||
await this.onReply('⏳ 该功能最近刚被修改过,请稍后再试');
|
await this.onReply('This feature was recently modified. Please try again later.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +148,7 @@ export class SlashCommandHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.state.lastToggle[feature] = Date.now();
|
this.state.lastToggle[feature] = Date.now();
|
||||||
await this.onReply(`✅ 已禁用 ${feature}`);
|
await this.onReply(`Disabled ${feature}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
private isValidFeature(feature: string): feature is 'pass-mgr' | 'safe-restart' {
|
private isValidFeature(feature: string): feature is 'pass-mgr' | 'safe-restart' {
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export { StatusManager, type AgentStatus, type GlobalStatus, type AgentState } from './status-manager';
|
export { StatusManager, type AgentStatus, type GlobalStatus, type AgentState } from './status-manager';
|
||||||
export { createApiServer, startApiServer } from './api';
|
export { createApiServer, startApiServer } from './api';
|
||||||
export { safeRestart, createSafeRestartTool, type SafeRestartOptions, type SafeRestartResult } from './safe-restart';
|
export { safeRestart, createSafeRestartTool, type SafeRestartOptions, type SafeRestartResult } from './safe-restart';
|
||||||
export { SlashCommandHandler, type SlashCommandOptions } from './slash-commands';
|
export { SlashCommandHandler, type SlashCommandOptions } from '../commands/slash-commands';
|
||||||
1
plugin/hooks/.gitkeep
Normal file
1
plugin/hooks/.gitkeep
Normal file
@@ -0,0 +1 @@
|
|||||||
|
# placeholder
|
||||||
227
plugin/index.ts
Normal file
227
plugin/index.ts
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
// PaddedCell Plugin for OpenClaw
|
||||||
|
// Registers pcexec and safe_restart tools
|
||||||
|
|
||||||
|
import { pcexec, pcexecSync } from './tools/pcexec';
|
||||||
|
import {
|
||||||
|
safeRestart,
|
||||||
|
createSafeRestartTool,
|
||||||
|
StatusManager,
|
||||||
|
createApiServer,
|
||||||
|
startApiServer,
|
||||||
|
} from './core/index';
|
||||||
|
import { SlashCommandHandler } from './commands/slash-commands';
|
||||||
|
import { EgoMgrSlashCommand } from './commands/ego-mgr-slash';
|
||||||
|
|
||||||
|
/** Sentinel value injected into every pcexec subprocess */
|
||||||
|
const AGENT_VERIFY = 'IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the openclaw base path.
|
||||||
|
* Priority: explicit config → $OPENCLAW_PATH → ~/.openclaw
|
||||||
|
*/
|
||||||
|
function resolveOpenclawPath(config?: { openclawProfilePath?: string }): string {
|
||||||
|
if (config?.openclawProfilePath) return config.openclawProfilePath;
|
||||||
|
if (process.env.OPENCLAW_PATH) return process.env.OPENCLAW_PATH;
|
||||||
|
const home = process.env.HOME || require('os').homedir();
|
||||||
|
return require('path').join(home, '.openclaw');
|
||||||
|
}
|
||||||
|
|
||||||
|
function getPluginConfig(api: any): Record<string, unknown> {
|
||||||
|
return ((api?.pluginConfig as Record<string, unknown> | undefined) || {});
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveProxyAllowlist(config?: { proxyAllowlist?: unknown; 'proxy-allowlist'?: unknown }): string[] {
|
||||||
|
const value = config?.proxyAllowlist ?? config?.['proxy-allowlist'];
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
return value.filter((item): item is string => typeof item === 'string');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plugin registration function
|
||||||
|
function register(api: any) {
|
||||||
|
const logger = api.logger || { info: console.log, error: console.error };
|
||||||
|
|
||||||
|
logger.info('PaddedCell plugin initializing...');
|
||||||
|
|
||||||
|
const pluginConfig = getPluginConfig(api);
|
||||||
|
const openclawPath = resolveOpenclawPath(pluginConfig as { openclawProfilePath?: string });
|
||||||
|
const proxyAllowlist = resolveProxyAllowlist(pluginConfig as { proxyAllowlist?: unknown; 'proxy-allowlist'?: unknown });
|
||||||
|
const binDir = require('path').join(openclawPath, 'bin');
|
||||||
|
|
||||||
|
// Register pcexec tool — pass a FACTORY function that receives context
|
||||||
|
api.registerTool((ctx: any) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
const workspaceDir = ctx.workspaceDir;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: 'pcexec',
|
||||||
|
description: 'Safe exec with password sanitization',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
command: { type: 'string', description: 'Command to execute' },
|
||||||
|
cwd: { type: 'string', description: 'Working directory' },
|
||||||
|
timeout: { type: 'number', description: 'Timeout in milliseconds' },
|
||||||
|
},
|
||||||
|
required: ['command'],
|
||||||
|
},
|
||||||
|
async execute(_id: string, params: any) {
|
||||||
|
const command = params.command;
|
||||||
|
if (!command) {
|
||||||
|
throw new Error('Missing required parameter: command');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build PATH with openclaw bin dir appended
|
||||||
|
const currentPath = process.env.PATH || '';
|
||||||
|
const newPath = currentPath.includes(binDir)
|
||||||
|
? currentPath
|
||||||
|
: `${currentPath}:${binDir}`;
|
||||||
|
|
||||||
|
const result = await pcexec(command, {
|
||||||
|
cwd: params.cwd || workspaceDir,
|
||||||
|
timeout: params.timeout,
|
||||||
|
env: {
|
||||||
|
AGENT_ID: agentId || '',
|
||||||
|
AGENT_WORKSPACE: workspaceDir || '',
|
||||||
|
AGENT_VERIFY,
|
||||||
|
PATH: newPath,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Format output for OpenClaw tool response
|
||||||
|
let output = result.stdout;
|
||||||
|
if (result.stderr) {
|
||||||
|
output += result.stderr;
|
||||||
|
}
|
||||||
|
return { content: [{ type: 'text', text: output }] };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
api.registerTool((ctx: any) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
const workspaceDir = ctx.workspaceDir;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: 'proxy-pcexec',
|
||||||
|
description: 'Safe exec with password sanitization using a proxied AGENT_ID',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
command: { type: 'string', description: 'Command to execute' },
|
||||||
|
cwd: { type: 'string', description: 'Working directory' },
|
||||||
|
timeout: { type: 'number', description: 'Timeout in milliseconds' },
|
||||||
|
'proxy-for': { type: 'string', description: 'AGENT_ID value to inject for the subprocess' },
|
||||||
|
},
|
||||||
|
required: ['command', 'proxy-for'],
|
||||||
|
},
|
||||||
|
async execute(_id: string, params: any) {
|
||||||
|
const command = params.command;
|
||||||
|
const proxyFor = params['proxy-for'];
|
||||||
|
if (!command) {
|
||||||
|
throw new Error('Missing required parameter: command');
|
||||||
|
}
|
||||||
|
if (!proxyFor) {
|
||||||
|
throw new Error('Missing required parameter: proxy-for');
|
||||||
|
}
|
||||||
|
if (!agentId || !proxyAllowlist.includes(agentId)) {
|
||||||
|
throw new Error('Current agent is not allowed to call proxy-pcexec');
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('proxy-pcexec invoked', {
|
||||||
|
executor: agentId,
|
||||||
|
proxyFor,
|
||||||
|
command,
|
||||||
|
});
|
||||||
|
|
||||||
|
const currentPath = process.env.PATH || '';
|
||||||
|
const newPath = currentPath.includes(binDir)
|
||||||
|
? currentPath
|
||||||
|
: `${currentPath}:${binDir}`;
|
||||||
|
|
||||||
|
const result = await pcexec(command, {
|
||||||
|
cwd: params.cwd || workspaceDir,
|
||||||
|
timeout: params.timeout,
|
||||||
|
env: {
|
||||||
|
AGENT_ID: String(proxyFor),
|
||||||
|
AGENT_WORKSPACE: workspaceDir || '',
|
||||||
|
AGENT_VERIFY,
|
||||||
|
PROXY_PCEXEC_EXECUTOR: agentId || '',
|
||||||
|
PCEXEC_PROXIED: 'true',
|
||||||
|
PATH: newPath,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let output = result.stdout;
|
||||||
|
if (result.stderr) {
|
||||||
|
output += result.stderr;
|
||||||
|
}
|
||||||
|
return { content: [{ type: 'text', text: output }] };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Register safe_restart tool
|
||||||
|
api.registerTool((ctx: any) => {
|
||||||
|
const agentId = ctx.agentId;
|
||||||
|
const sessionKey = ctx.sessionKey;
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: 'safe_restart',
|
||||||
|
description: 'Safe coordinated restart of OpenClaw gateway',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
rollback: { type: 'string', description: 'Rollback script path' },
|
||||||
|
log: { type: 'string', description: 'Log file path' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async execute(_id: string, params: any) {
|
||||||
|
return await safeRestart({
|
||||||
|
agentId,
|
||||||
|
sessionKey,
|
||||||
|
rollback: params.rollback,
|
||||||
|
log: params.log,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Register /ego-mgr slash command
|
||||||
|
if (api.registerSlashCommand) {
|
||||||
|
api.registerSlashCommand({
|
||||||
|
name: 'ego-mgr',
|
||||||
|
description: 'Manage agent identity/profile fields',
|
||||||
|
handler: async (ctx: any, command: string) => {
|
||||||
|
const egoMgrSlash = new EgoMgrSlashCommand({
|
||||||
|
openclawPath,
|
||||||
|
agentId: ctx.agentId || '',
|
||||||
|
workspaceDir: ctx.workspaceDir || '',
|
||||||
|
onReply: async (message: string) => {
|
||||||
|
if (ctx.reply) {
|
||||||
|
await ctx.reply(message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await egoMgrSlash.handle(command);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
logger.info('Registered /ego-mgr slash command');
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('PaddedCell plugin initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
// CommonJS export for OpenClaw
|
||||||
|
module.exports = { register };
|
||||||
|
|
||||||
|
// Also export individual modules for direct use
|
||||||
|
module.exports.pcexec = pcexec;
|
||||||
|
module.exports.pcexecSync = pcexecSync;
|
||||||
|
module.exports.safeRestart = safeRestart;
|
||||||
|
module.exports.createSafeRestartTool = createSafeRestartTool;
|
||||||
|
module.exports.StatusManager = StatusManager;
|
||||||
|
module.exports.createApiServer = createApiServer;
|
||||||
|
module.exports.startApiServer = startApiServer;
|
||||||
|
module.exports.SlashCommandHandler = SlashCommandHandler;
|
||||||
|
module.exports.EgoMgrSlashCommand = EgoMgrSlashCommand;
|
||||||
|
module.exports.AGENT_VERIFY = AGENT_VERIFY;
|
||||||
20
plugin/openclaw.plugin.json
Normal file
20
plugin/openclaw.plugin.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"id": "padded-cell",
|
||||||
|
"name": "PaddedCell",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"description": "Secure secret management, agent identity management, safe execution, and coordinated agent restart",
|
||||||
|
"entry": "./index.js",
|
||||||
|
"configSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"enabled": { "type": "boolean", "default": true },
|
||||||
|
"secretMgrPath": { "type": "string", "default": "" },
|
||||||
|
"openclawProfilePath": { "type": "string", "default": "" },
|
||||||
|
"proxyAllowlist": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"default": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
plugin/package.json
Normal file
20
plugin/package.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "padded-cell-plugin",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"description": "PaddedCell plugin for OpenClaw - secure exec, password management, coordinated restart",
|
||||||
|
"main": "index.ts",
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"dev": "tsc --watch"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "^20.0.0",
|
||||||
|
"express": "^4.18.0",
|
||||||
|
"ws": "^8.14.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"typescript": "^5.0.0",
|
||||||
|
"@types/express": "^4.17.0",
|
||||||
|
"@types/ws": "^8.5.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
339
plugin/tools/pcexec.ts
Normal file
339
plugin/tools/pcexec.ts
Normal file
@@ -0,0 +1,339 @@
|
|||||||
|
import { spawn, SpawnOptions } from 'child_process';
|
||||||
|
|
||||||
|
export interface PcExecOptions {
|
||||||
|
/** Current working directory */
|
||||||
|
cwd?: string;
|
||||||
|
/** Environment variables */
|
||||||
|
env?: Record<string, string>;
|
||||||
|
/** Timeout in milliseconds */
|
||||||
|
timeout?: number;
|
||||||
|
/** Maximum buffer size for stdout/stderr */
|
||||||
|
maxBuffer?: number;
|
||||||
|
/** Kill signal */
|
||||||
|
killSignal?: NodeJS.Signals;
|
||||||
|
/** Shell to use */
|
||||||
|
shell?: string | boolean;
|
||||||
|
/** UID to run as */
|
||||||
|
uid?: number;
|
||||||
|
/** GID to run as */
|
||||||
|
gid?: number;
|
||||||
|
/** Window style (Windows only) */
|
||||||
|
windowsHide?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PcExecResult {
|
||||||
|
/** Standard output */
|
||||||
|
stdout: string;
|
||||||
|
/** Standard error */
|
||||||
|
stderr: string;
|
||||||
|
/** Exit code */
|
||||||
|
exitCode: number;
|
||||||
|
/** Command that was executed */
|
||||||
|
command: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PcExecError extends Error {
|
||||||
|
/** Exit code */
|
||||||
|
code?: number;
|
||||||
|
/** Signal that terminated the process */
|
||||||
|
signal?: string;
|
||||||
|
/** Standard output */
|
||||||
|
stdout: string;
|
||||||
|
/** Standard error */
|
||||||
|
stderr: string;
|
||||||
|
/** Killed by timeout */
|
||||||
|
killed?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract secret-mgr (and legacy pass_mgr) invocations from a command string.
|
||||||
|
*
|
||||||
|
* Supports:
|
||||||
|
* Current: $(secret-mgr get-secret --key <key>) / `secret-mgr get-secret --key <key>`
|
||||||
|
* Legacy: $(pass_mgr get-secret --key <key>) / `pass_mgr get-secret --key <key>`
|
||||||
|
* Legacy: $(pass_mgr get <key>) / `pass_mgr get <key>`
|
||||||
|
*
|
||||||
|
* Returns array of { fullMatch, subcommand, key, binary } where subcommand is
|
||||||
|
* "get" | "get-secret".
|
||||||
|
*/
|
||||||
|
function extractSecretMgrGets(
|
||||||
|
command: string,
|
||||||
|
): Array<{ key: string; fullMatch: string; subcommand: string; binary: string }> {
|
||||||
|
const results: Array<{ key: string; fullMatch: string; subcommand: string; binary: string }> = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
// secret-mgr get-secret --key <key>
|
||||||
|
const secretMgrPatterns = [
|
||||||
|
/\$\(\s*secret-mgr\s+get-secret\s+--key\s+(\S+)\s*\)/g,
|
||||||
|
/`\s*secret-mgr\s+get-secret\s+--key\s+(\S+)\s*`/g,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Legacy pass_mgr get-secret --key <key>
|
||||||
|
const newPatterns = [
|
||||||
|
/\$\(\s*pass_mgr\s+get-secret\s+--key\s+(\S+)\s*\)/g,
|
||||||
|
/`\s*pass_mgr\s+get-secret\s+--key\s+(\S+)\s*`/g,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Legacy pass_mgr get <key>
|
||||||
|
const legacyPatterns = [
|
||||||
|
/\$\(\s*pass_mgr\s+get\s+(\S+)\s*\)/g,
|
||||||
|
/`\s*pass_mgr\s+get\s+(\S+)\s*`/g,
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const pattern of secretMgrPatterns) {
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(command)) !== null) {
|
||||||
|
if (!seen.has(match[0])) {
|
||||||
|
seen.add(match[0]);
|
||||||
|
results.push({
|
||||||
|
key: match[1],
|
||||||
|
fullMatch: match[0],
|
||||||
|
subcommand: 'get-secret',
|
||||||
|
binary: 'secret-mgr',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const pattern of newPatterns) {
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(command)) !== null) {
|
||||||
|
if (!seen.has(match[0])) {
|
||||||
|
seen.add(match[0]);
|
||||||
|
results.push({
|
||||||
|
key: match[1],
|
||||||
|
fullMatch: match[0],
|
||||||
|
subcommand: 'get-secret',
|
||||||
|
binary: 'pass_mgr',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const pattern of legacyPatterns) {
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(command)) !== null) {
|
||||||
|
if (!seen.has(match[0])) {
|
||||||
|
seen.add(match[0]);
|
||||||
|
results.push({
|
||||||
|
key: match[1],
|
||||||
|
fullMatch: match[0],
|
||||||
|
subcommand: 'get',
|
||||||
|
binary: 'pass_mgr',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute secret-mgr (or legacy pass_mgr) to retrieve a secret.
|
||||||
|
* Uses the same env vars that the caller passes so pcguard checks pass.
|
||||||
|
*/
|
||||||
|
async function fetchPassword(
|
||||||
|
subcommand: string,
|
||||||
|
key: string,
|
||||||
|
env: Record<string, string>,
|
||||||
|
binary: string = 'secret-mgr',
|
||||||
|
): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
// Prefer SECRET_MGR_PATH, fall back to PASS_MGR_PATH for legacy compat
|
||||||
|
const binaryPath = env.SECRET_MGR_PATH || env.PASS_MGR_PATH || process.env.SECRET_MGR_PATH || process.env.PASS_MGR_PATH || 'secret-mgr';
|
||||||
|
const args =
|
||||||
|
subcommand === 'get-secret'
|
||||||
|
? ['get-secret', '--key', key]
|
||||||
|
: ['get', key];
|
||||||
|
|
||||||
|
const child = spawn(binaryPath, args, {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
env: { ...process.env, ...env },
|
||||||
|
});
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
child.stdout.on('data', (d) => (stdout += d.toString()));
|
||||||
|
child.stderr.on('data', (d) => (stderr += d.toString()));
|
||||||
|
child.on('close', (code) => {
|
||||||
|
if (code !== 0) {
|
||||||
|
reject(new Error(`secret-mgr ${subcommand} failed: ${stderr || stdout}`));
|
||||||
|
} else {
|
||||||
|
resolve(stdout.trim());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
child.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize output by replacing passwords with ######
|
||||||
|
*/
|
||||||
|
function sanitizeOutput(output: string, passwords: string[]): string {
|
||||||
|
let sanitized = output;
|
||||||
|
for (const password of passwords) {
|
||||||
|
if (password) {
|
||||||
|
const escaped = password.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
sanitized = sanitized.replace(new RegExp(escaped, 'g'), '######');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sanitized;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pre-resolve secret-mgr (and legacy pass_mgr) invocations, replace them inline, and collect passwords.
|
||||||
|
*/
|
||||||
|
async function replaceSecretMgrGets(
|
||||||
|
command: string,
|
||||||
|
env: Record<string, string>,
|
||||||
|
): Promise<{ command: string; passwords: string[] }> {
|
||||||
|
const matches = extractSecretMgrGets(command);
|
||||||
|
const passwords: string[] = [];
|
||||||
|
let replaced = command;
|
||||||
|
|
||||||
|
for (const { key, fullMatch, subcommand, binary } of matches) {
|
||||||
|
const pw = await fetchPassword(subcommand, key, env, binary);
|
||||||
|
passwords.push(pw);
|
||||||
|
replaced = replaced.split(fullMatch).join(pw);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { command: replaced, passwords };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Safe exec wrapper that handles secret-mgr get commands and sanitizes output.
|
||||||
|
*/
|
||||||
|
export async function pcexec(
|
||||||
|
command: string,
|
||||||
|
options: PcExecOptions = {},
|
||||||
|
): Promise<PcExecResult> {
|
||||||
|
// Build environment
|
||||||
|
const env: Record<string, string> = {};
|
||||||
|
|
||||||
|
for (const [k, v] of Object.entries(process.env)) {
|
||||||
|
if (v !== undefined) env[k] = v;
|
||||||
|
}
|
||||||
|
if (options.env) Object.assign(env, options.env);
|
||||||
|
|
||||||
|
// Pre-resolve passwords
|
||||||
|
let finalCommand = command;
|
||||||
|
let passwords: string[] = [];
|
||||||
|
|
||||||
|
const resolved = await replaceSecretMgrGets(command, env);
|
||||||
|
finalCommand = resolved.command;
|
||||||
|
passwords = resolved.passwords;
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const spawnOptions: SpawnOptions = {
|
||||||
|
cwd: options.cwd,
|
||||||
|
env,
|
||||||
|
shell: options.shell,
|
||||||
|
windowsHide: options.windowsHide,
|
||||||
|
uid: options.uid,
|
||||||
|
gid: options.gid,
|
||||||
|
};
|
||||||
|
|
||||||
|
const child = spawn('bash', ['-c', finalCommand], spawnOptions);
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
let killed = false;
|
||||||
|
let timeoutId: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
if (options.timeout && options.timeout > 0) {
|
||||||
|
timeoutId = setTimeout(() => {
|
||||||
|
killed = true;
|
||||||
|
child.kill(options.killSignal || 'SIGTERM');
|
||||||
|
}, options.timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
child.stdout?.on('data', (data) => {
|
||||||
|
stdout += data.toString();
|
||||||
|
if (options.maxBuffer && stdout.length > options.maxBuffer) {
|
||||||
|
child.kill(options.killSignal || 'SIGTERM');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stderr?.on('data', (data) => {
|
||||||
|
stderr += data.toString();
|
||||||
|
if (options.maxBuffer && stderr.length > options.maxBuffer) {
|
||||||
|
child.kill(options.killSignal || 'SIGTERM');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('close', (code, signal) => {
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
|
||||||
|
const sanitizedStdout = sanitizeOutput(stdout, passwords);
|
||||||
|
const sanitizedStderr = sanitizeOutput(stderr, passwords);
|
||||||
|
|
||||||
|
if (code === 0) {
|
||||||
|
resolve({
|
||||||
|
stdout: sanitizedStdout,
|
||||||
|
stderr: sanitizedStderr,
|
||||||
|
exitCode: 0,
|
||||||
|
command: finalCommand,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const error = new Error(`Command failed: ${command}\n${stderr}`) as PcExecError;
|
||||||
|
error.code = code ?? undefined;
|
||||||
|
error.signal = signal ?? undefined;
|
||||||
|
error.stdout = sanitizedStdout;
|
||||||
|
error.stderr = sanitizedStderr;
|
||||||
|
error.killed = killed;
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('error', (err) => {
|
||||||
|
if (timeoutId) clearTimeout(timeoutId);
|
||||||
|
const error = new Error(`Failed to execute command: ${err.message}`) as PcExecError;
|
||||||
|
error.stdout = sanitizeOutput(stdout, passwords);
|
||||||
|
error.stderr = sanitizeOutput(stderr, passwords);
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Synchronous version — password substitution is NOT supported here
|
||||||
|
* (use async pcexec for secret-mgr integration).
|
||||||
|
*/
|
||||||
|
export function pcexecSync(
|
||||||
|
command: string,
|
||||||
|
options: PcExecOptions = {},
|
||||||
|
): PcExecResult {
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
|
||||||
|
const env: Record<string, string> = {};
|
||||||
|
for (const [k, v] of Object.entries(process.env)) {
|
||||||
|
if (v !== undefined) env[k] = v;
|
||||||
|
}
|
||||||
|
if (options.env) Object.assign(env, options.env);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stdout = execSync(command, {
|
||||||
|
cwd: options.cwd,
|
||||||
|
env,
|
||||||
|
shell: options.shell as any,
|
||||||
|
encoding: 'utf8',
|
||||||
|
windowsHide: options.windowsHide,
|
||||||
|
uid: options.uid,
|
||||||
|
gid: options.gid,
|
||||||
|
maxBuffer: options.maxBuffer,
|
||||||
|
timeout: options.timeout,
|
||||||
|
killSignal: options.killSignal,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { stdout: stdout.toString(), stderr: '', exitCode: 0, command };
|
||||||
|
} catch (err: any) {
|
||||||
|
const error = new Error(`Command failed: ${command}`) as PcExecError;
|
||||||
|
error.code = err.status;
|
||||||
|
error.signal = err.signal;
|
||||||
|
error.stdout = err.stdout?.toString() || '';
|
||||||
|
error.stderr = err.stderr?.toString() || '';
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default pcexec;
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
"target": "ES2020",
|
"target": "ES2020",
|
||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"lib": ["ES2020"],
|
"lib": ["ES2020"],
|
||||||
"outDir": "./dist",
|
"outDir": "../dist/padded-cell",
|
||||||
"rootDir": "./src",
|
"rootDir": ".",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
@@ -14,6 +14,6 @@
|
|||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"resolveJsonModule": true
|
"resolveJsonModule": true
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"],
|
"include": ["./**/*.ts"],
|
||||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
"exclude": ["node_modules", "../dist", "**/*.test.ts"]
|
||||||
}
|
}
|
||||||
4821
safe-restart/package-lock.json
generated
4821
safe-restart/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,25 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "safe-restart",
|
|
||||||
"version": "0.1.0",
|
|
||||||
"description": "Safe restart module for OpenClaw agents",
|
|
||||||
"main": "dist/index.js",
|
|
||||||
"types": "dist/index.d.ts",
|
|
||||||
"scripts": {
|
|
||||||
"build": "tsc",
|
|
||||||
"dev": "tsc --watch",
|
|
||||||
"test": "jest"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@types/node": "^20.0.0",
|
|
||||||
"express": "^4.18.0",
|
|
||||||
"ws": "^8.14.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"typescript": "^5.0.0",
|
|
||||||
"@types/express": "^4.17.0",
|
|
||||||
"@types/ws": "^8.5.0",
|
|
||||||
"jest": "^29.0.0",
|
|
||||||
"@types/jest": "^29.0.0",
|
|
||||||
"ts-jest": "^29.0.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
10
secret-mgr/go.mod
Normal file
10
secret-mgr/go.mod
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
module secret-mgr
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
|
|
||||||
|
require github.com/spf13/cobra v1.8.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
|
)
|
||||||
10
secret-mgr/go.sum
Normal file
10
secret-mgr/go.sum
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
|
||||||
|
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
|
||||||
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
|
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
541
secret-mgr/src/main.go
Normal file
541
secret-mgr/src/main.go
Normal file
@@ -0,0 +1,541 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
// buildSecret is injected at compile time via -ldflags "-X main.buildSecret=<hex>"
|
||||||
|
var buildSecret string
|
||||||
|
|
||||||
|
const (
|
||||||
|
PassStoreDirName = "pc-pass-store"
|
||||||
|
PublicDirName = ".public"
|
||||||
|
|
||||||
|
// Must match pcguard sentinel
|
||||||
|
expectedAgentVerify = "IF YOU ARE AN AGENT/MODEL, YOU SHOULD NEVER TOUCH THIS ENV VARIABLE"
|
||||||
|
)
|
||||||
|
|
||||||
|
// EncryptedFile is the on-disk format for .gpg files
|
||||||
|
// (kept for compatibility with existing files)
|
||||||
|
type EncryptedFile struct {
|
||||||
|
Nonce string `json:"nonce"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry is the plaintext content inside an encrypted file
|
||||||
|
type Entry struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveOpenclawPath() string {
|
||||||
|
if p := os.Getenv("OPENCLAW_PATH"); p != "" {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
return filepath.Join(home, ".openclaw")
|
||||||
|
}
|
||||||
|
|
||||||
|
func passStoreBase() string { return filepath.Join(resolveOpenclawPath(), PassStoreDirName) }
|
||||||
|
func publicStoreDir() string { return filepath.Join(passStoreBase(), PublicDirName) }
|
||||||
|
func agentStoreDir(agentID string) string { return filepath.Join(passStoreBase(), agentID) }
|
||||||
|
func currentAgentID() string { return os.Getenv("AGENT_ID") }
|
||||||
|
func resolveStoreDir(public bool) string {
|
||||||
|
if public {
|
||||||
|
return publicStoreDir()
|
||||||
|
}
|
||||||
|
return agentStoreDir(currentAgentID())
|
||||||
|
}
|
||||||
|
func ensurePublicStoreDir() error { return os.MkdirAll(publicStoreDir(), 0700) }
|
||||||
|
func deriveKey(secret string) []byte { h := sha256.Sum256([]byte(secret)); return h[:] }
|
||||||
|
func anyAgentEnvSet() bool {
|
||||||
|
return os.Getenv("AGENT_ID") != "" || os.Getenv("AGENT_WORKSPACE") != "" || os.Getenv("AGENT_VERIFY") != ""
|
||||||
|
}
|
||||||
|
func rejectIfAgent(cmdName string) {
|
||||||
|
if anyAgentEnvSet() {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: '%s' can only be run by a human (AGENT_* env vars detected)\n", cmdName)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentKey() ([]byte, error) {
|
||||||
|
if buildSecret == "" {
|
||||||
|
return nil, fmt.Errorf("secret-mgr was built without a build secret; re-run install.mjs")
|
||||||
|
}
|
||||||
|
return deriveKey(buildSecret), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encrypt(plaintext, key []byte) (*EncryptedFile, error) {
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
gcm, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
nonce := make([]byte, gcm.NonceSize())
|
||||||
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
|
||||||
|
return &EncryptedFile{Nonce: base64.StdEncoding.EncodeToString(nonce), Data: base64.StdEncoding.EncodeToString(ciphertext)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decrypt(ef *EncryptedFile, key []byte) ([]byte, error) {
|
||||||
|
nonce, err := base64.StdEncoding.DecodeString(ef.Nonce)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid nonce: %w", err)
|
||||||
|
}
|
||||||
|
ciphertext, err := base64.StdEncoding.DecodeString(ef.Data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid data: %w", err)
|
||||||
|
}
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
gcm, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return gcm.Open(nil, nonce, ciphertext, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readEntry(filePath string, key []byte) (*Entry, error) {
|
||||||
|
raw, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var ef EncryptedFile
|
||||||
|
if err := json.Unmarshal(raw, &ef); err != nil {
|
||||||
|
return nil, fmt.Errorf("corrupt file: %w", err)
|
||||||
|
}
|
||||||
|
plain, err := decrypt(&ef, key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decryption failed: %w", err)
|
||||||
|
}
|
||||||
|
var entry Entry
|
||||||
|
if err := json.Unmarshal(plain, &entry); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid entry json: %w", err)
|
||||||
|
}
|
||||||
|
return &entry, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeEntry(filePath string, entry *Entry, key []byte) error {
|
||||||
|
plain, _ := json.Marshal(entry)
|
||||||
|
ef, err := encrypt(plain, key)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, _ := json.MarshalIndent(ef, "", " ")
|
||||||
|
return os.WriteFile(filePath, data, 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requirePcguard() {
|
||||||
|
if os.Getenv("AGENT_VERIFY") != expectedAgentVerify {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: must be invoked via pcexec (AGENT_VERIFY mismatch)")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_ID") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_ID not set — must be invoked via pcexec")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if os.Getenv("AGENT_WORKSPACE") == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: AGENT_WORKSPACE not set — must be invoked via pcexec")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func generatePassword(length int) (string, error) {
|
||||||
|
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+"
|
||||||
|
buf := make([]byte, length)
|
||||||
|
for i := range buf {
|
||||||
|
b := make([]byte, 1)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
buf[i] = charset[int(b[0])%len(charset)]
|
||||||
|
}
|
||||||
|
return string(buf), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
rootCmd := &cobra.Command{Use: "secret-mgr", Short: "Secret manager for OpenClaw agents"}
|
||||||
|
rootCmd.AddCommand(listCmd(), getSecretCmd(), getUsernameCmd(), getLegacyCmd(), setCmd(), generateCmd(), unsetCmd(), adminCmd())
|
||||||
|
if err := rootCmd.Execute(); err != nil {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listKeys(dir string) []string {
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
out := []string{}
|
||||||
|
for _, e := range entries {
|
||||||
|
name := e.Name()
|
||||||
|
if strings.HasSuffix(name, ".gpg") {
|
||||||
|
out = append(out, strings.TrimSuffix(name, ".gpg"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func listCmd() *cobra.Command {
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Short: "List keys for current agent",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if public {
|
||||||
|
fmt.Println("----------public------------")
|
||||||
|
for _, k := range listKeys(publicStoreDir()) {
|
||||||
|
fmt.Println(k)
|
||||||
|
}
|
||||||
|
fmt.Println("----------private-----------")
|
||||||
|
for _, k := range listKeys(agentStoreDir(currentAgentID())) {
|
||||||
|
fmt.Println(k)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, k := range listKeys(agentStoreDir(currentAgentID())) {
|
||||||
|
fmt.Println(k)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Include shared public scope")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getSecretCmd() *cobra.Command {
|
||||||
|
var keyFlag string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get-secret",
|
||||||
|
Aliases: []string{"get_secret"},
|
||||||
|
Short: "Get secret for a key",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
key, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
|
||||||
|
entry, err := readEntry(fp, key)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Print(entry.Secret)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getUsernameCmd() *cobra.Command {
|
||||||
|
var keyFlag string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get-username",
|
||||||
|
Aliases: []string{"get_username"},
|
||||||
|
Short: "Get username for a key",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
key, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
|
||||||
|
entry, err := readEntry(fp, key)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Print(entry.Username)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLegacyCmd() *cobra.Command {
|
||||||
|
var showUsername bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "get [key]",
|
||||||
|
Short: "Get secret (legacy — use get-secret --key instead)",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
Hidden: true,
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
keyName := args[0]
|
||||||
|
key, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(agentStoreDir(currentAgentID()), keyName+".gpg")
|
||||||
|
entry, err := readEntry(fp, key)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if showUsername {
|
||||||
|
fmt.Print(entry.Username)
|
||||||
|
} else {
|
||||||
|
fmt.Print(entry.Secret)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().BoolVar(&showUsername, "username", false, "Show username instead of secret")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func setCmd() *cobra.Command {
|
||||||
|
var keyFlag, username, secret string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "set",
|
||||||
|
Short: "Set a key entry",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" || secret == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key and --secret are required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
aesKey, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
dir := resolveStoreDir(public)
|
||||||
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := ensurePublicStoreDir(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
entry := &Entry{Username: username, Secret: secret}
|
||||||
|
fp := filepath.Join(dir, keyFlag+".gpg")
|
||||||
|
if err := writeEntry(fp, entry, aesKey); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().StringVar(&username, "username", "", "Username")
|
||||||
|
cmd.Flags().StringVar(&secret, "secret", "", "Secret value")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateCmd() *cobra.Command {
|
||||||
|
var keyFlag, username string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "generate",
|
||||||
|
Short: "Generate a random secret for a key",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
aesKey, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
pw, err := generatePassword(32)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
dir := resolveStoreDir(public)
|
||||||
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := ensurePublicStoreDir(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
entry := &Entry{Username: username, Secret: pw}
|
||||||
|
fp := filepath.Join(dir, keyFlag+".gpg")
|
||||||
|
if err := writeEntry(fp, entry, aesKey); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Print(pw)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().StringVar(&username, "username", "", "Username")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func unsetCmd() *cobra.Command {
|
||||||
|
var keyFlag string
|
||||||
|
var public bool
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "unset",
|
||||||
|
Short: "Remove a key entry",
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
requirePcguard()
|
||||||
|
if keyFlag == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: --key is required")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fp := filepath.Join(resolveStoreDir(public), keyFlag+".gpg")
|
||||||
|
if err := os.Remove(fp); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&keyFlag, "key", "", "Key name")
|
||||||
|
cmd.Flags().BoolVar(&public, "public", false, "Use shared public scope only")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func adminCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{Use: "admin", Short: "Admin commands (human only)"}
|
||||||
|
cmd.AddCommand(adminHandoffCmd(), adminInitFromCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func adminHandoffCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "handoff [secret_file_path]",
|
||||||
|
Short: "Export build secret to file for migration",
|
||||||
|
Args: cobra.MaximumNArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
rejectIfAgent("admin handoff")
|
||||||
|
if buildSecret == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: no build secret compiled in")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
outPath := "pc-pass-store.secret"
|
||||||
|
if len(args) > 0 {
|
||||||
|
outPath = args[0]
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(outPath, []byte(buildSecret), 0600); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Build secret written to %s\n", outPath)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func adminInitFromCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "init-from [secret_file_path]",
|
||||||
|
Aliases: []string{"init_from"},
|
||||||
|
Short: "Re-encrypt all data from old build secret to current",
|
||||||
|
Args: cobra.MaximumNArgs(1),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
rejectIfAgent("admin init-from")
|
||||||
|
|
||||||
|
inPath := "pc-pass-store.secret"
|
||||||
|
if len(args) > 0 {
|
||||||
|
inPath = args[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
oldSecretBytes, err := os.ReadFile(inPath)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error reading secret file: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
oldSecret := strings.TrimSpace(string(oldSecretBytes))
|
||||||
|
oldKey := deriveKey(oldSecret)
|
||||||
|
|
||||||
|
newKey, err := currentKey()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = ensurePublicStoreDir()
|
||||||
|
base := passStoreBase()
|
||||||
|
dirs, err := os.ReadDir(base)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
fmt.Fprintln(os.Stderr, "No pass store found — nothing to migrate")
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
count := 0
|
||||||
|
for _, d := range dirs {
|
||||||
|
if !d.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
scopeDir := filepath.Join(base, d.Name())
|
||||||
|
files, err := os.ReadDir(scopeDir)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, f := range files {
|
||||||
|
if !strings.HasSuffix(f.Name(), ".gpg") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fp := filepath.Join(scopeDir, f.Name())
|
||||||
|
entry, err := readEntry(fp, oldKey)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: failed to decrypt %s: %v\n", fp, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := writeEntry(fp, entry, newKey); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: failed to re-encrypt %s: %v\n", fp, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Remove(inPath); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Warning: could not remove secret file: %v\n", err)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "Re-encrypted %d entries. Secret file removed.\n", count)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
105
skills/ego-mgr/SKILL.md
Normal file
105
skills/ego-mgr/SKILL.md
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
---
|
||||||
|
name: ego-mgr
|
||||||
|
description: Manage agent personal information (name, email, timezone, etc.). Use when storing, retrieving, listing, or managing agent profile fields. Trigger on requests about agent identity, personal info, profile settings, or ego-mgr usage. MUST call ego-mgr via the pcexec tool.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Ego Manager
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Use ego-mgr to manage agent personal information fields. Supports per-agent fields (Agent Scope) and shared fields (Public Scope).
|
||||||
|
|
||||||
|
## Mandatory safety rule
|
||||||
|
Always invoke ego-mgr through the `pcexec` tool. Do NOT run ego-mgr directly.
|
||||||
|
|
||||||
|
## Concepts
|
||||||
|
|
||||||
|
- **Agent Scope columns**: Each agent stores its own value independently
|
||||||
|
- **Public Scope columns**: All agents share the same value
|
||||||
|
- Column names are globally unique — a name cannot be both agent-scope and public-scope
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. First, create a column: `ego-mgr add column <name>` or `ego-mgr add public-column <name>`
|
||||||
|
2. Then, set its value: `ego-mgr set <name> <value>`
|
||||||
|
3. Read it: `ego-mgr get <name>` or `ego-mgr show`
|
||||||
|
|
||||||
|
## Commands (run via pcexec)
|
||||||
|
|
||||||
|
### Add columns
|
||||||
|
```bash
|
||||||
|
# Agent-scope column (per-agent values)
|
||||||
|
ego-mgr add column <column-name> [--default <default-value>]
|
||||||
|
|
||||||
|
# Public-scope column (shared by all agents)
|
||||||
|
ego-mgr add public-column <column-name> [--default <default-value>]
|
||||||
|
```
|
||||||
|
|
||||||
|
### Delete a column
|
||||||
|
```bash
|
||||||
|
ego-mgr delete <column-name>
|
||||||
|
```
|
||||||
|
Removes the column and all its values across all scopes.
|
||||||
|
|
||||||
|
### Set a value
|
||||||
|
```bash
|
||||||
|
ego-mgr set <column-name> <value>
|
||||||
|
```
|
||||||
|
Automatically writes to the correct scope (agent or public) based on column type.
|
||||||
|
|
||||||
|
### Get a value
|
||||||
|
```bash
|
||||||
|
ego-mgr get <column-name>
|
||||||
|
```
|
||||||
|
Outputs just the value (no label).
|
||||||
|
|
||||||
|
### Show all fields
|
||||||
|
```bash
|
||||||
|
ego-mgr show
|
||||||
|
```
|
||||||
|
Lists all fields with values (public first, then agent-scope).
|
||||||
|
|
||||||
|
### List column names
|
||||||
|
```bash
|
||||||
|
ego-mgr list columns
|
||||||
|
```
|
||||||
|
Lists all column names (public first, then agent-scope).
|
||||||
|
|
||||||
|
## Error exit codes
|
||||||
|
|
||||||
|
| Code | Meaning |
|
||||||
|
|------|---------|
|
||||||
|
| 0 | Success |
|
||||||
|
| 1 | Usage error |
|
||||||
|
| 2 | Column not found |
|
||||||
|
| 3 | Column already exists |
|
||||||
|
| 4 | Permission error (not via pcexec) |
|
||||||
|
| 5 | File lock failed |
|
||||||
|
| 6 | JSON read/write error |
|
||||||
|
|
||||||
|
## Common use cases
|
||||||
|
|
||||||
|
### Set up agent identity
|
||||||
|
```bash
|
||||||
|
ego-mgr add column name
|
||||||
|
ego-mgr set name "小智"
|
||||||
|
ego-mgr add column email
|
||||||
|
ego-mgr set email "zhi@example.com"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Set shared config
|
||||||
|
```bash
|
||||||
|
ego-mgr add public-column timezone --default UTC
|
||||||
|
ego-mgr add public-column language --default zh-CN
|
||||||
|
```
|
||||||
|
|
||||||
|
### Check current profile
|
||||||
|
```bash
|
||||||
|
ego-mgr show
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage notes
|
||||||
|
|
||||||
|
- Always create columns before setting values
|
||||||
|
- Column names are case-sensitive
|
||||||
|
- Public scope values are readable and writable by all agents
|
||||||
|
- Agent scope values are isolated per-agent
|
||||||
68
skills/secret-mgr/SKILL.md
Normal file
68
skills/secret-mgr/SKILL.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
---
|
||||||
|
name: secret-mgr
|
||||||
|
description: Manage OpenClaw agent credentials (usernames/secrets). Use when storing, retrieving, listing, generating, or removing credentials for an agent. Trigger on requests about saving or fetching usernames, passwords, tokens, API keys, or other secrets. MUST call secret-mgr via the pcexec tool.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Secret Manager
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
Use secret-mgr to store and retrieve agent-scoped credentials (username/secret pairs) and generate secrets.
|
||||||
|
|
||||||
|
## Mandatory safety rule
|
||||||
|
Always invoke secret-mgr through the `pcexec` tool. Do NOT run secret-mgr directly.
|
||||||
|
|
||||||
|
## Commands (run via pcexec)
|
||||||
|
|
||||||
|
- List keys for current agent
|
||||||
|
- `secret-mgr list`
|
||||||
|
- Include shared scope: `secret-mgr list --public`
|
||||||
|
|
||||||
|
- Get username for a key
|
||||||
|
- `secret-mgr get-username --key <key>`
|
||||||
|
- Shared scope: `secret-mgr get-username --public --key <key>`
|
||||||
|
|
||||||
|
- Get secret for a key
|
||||||
|
- `secret-mgr get-secret --key <key>`
|
||||||
|
- Shared scope: `secret-mgr get-secret --public --key <key>`
|
||||||
|
|
||||||
|
- Set a key entry (username optional)
|
||||||
|
- `secret-mgr set --key <key> --secret <secret> [--username <username>]`
|
||||||
|
- Shared scope: `secret-mgr set --public --key <key> --secret <secret> [--username <username>]`
|
||||||
|
|
||||||
|
- Remove a key entry
|
||||||
|
- `secret-mgr unset --key <key>`
|
||||||
|
- Shared scope: `secret-mgr unset --public --key <key>`
|
||||||
|
|
||||||
|
- Generate a random secret for a key (prints secret)
|
||||||
|
- `secret-mgr generate --key <key> [--username <username>]`
|
||||||
|
- Shared scope: `secret-mgr generate --public --key <key> [--username <username>]`
|
||||||
|
|
||||||
|
- Legacy (hidden) getter
|
||||||
|
- `secret-mgr get <key>`
|
||||||
|
|
||||||
|
## Usage notes
|
||||||
|
|
||||||
|
- Treat all outputs as sensitive. Never echo secrets.
|
||||||
|
- When the agent needs credentials to access a resource, first try `list` to see if a matching key already exists before asking the user.
|
||||||
|
- Prefer `generate` when the user wants a new secret or password.
|
||||||
|
- Use `set` to store both username and secret in one step.
|
||||||
|
- Use `get-username` and `get-secret` for retrieval.
|
||||||
|
- Storing can be explicit (user asks) or proactive after the agent successfully registers/creates an account.
|
||||||
|
- Secrets should be fetched and used immediately in a command, not displayed (e.g., `xxx_cli login --user $(secret-mgr get-username --key some_key) --pass $(secret-mgr get-secret --key some_key)`).
|
||||||
|
|
||||||
|
## Examples (pcexec)
|
||||||
|
|
||||||
|
- Store credentials
|
||||||
|
- pcexec: `secret-mgr set --key github --username alice --secret <secret>`
|
||||||
|
|
||||||
|
- Retrieve username
|
||||||
|
- pcexec: `secret-mgr get-username --key github`
|
||||||
|
|
||||||
|
- Retrieve secret
|
||||||
|
- pcexec: `secret-mgr get-secret --key github`
|
||||||
|
|
||||||
|
- Generate secret
|
||||||
|
- pcexec: `secret-mgr generate --key github`
|
||||||
|
|
||||||
|
- Delete entry
|
||||||
|
- pcexec: `secret-mgr unset --key github`
|
||||||
Reference in New Issue
Block a user