# @edgeai/edge-client-ts

[![npm version](https://img.shields.io/npm/v/@edgeai/edge-client-ts.svg)](https://www.npmjs.com/package/@edgeai/edge-client-ts)
[![npm downloads](https://img.shields.io/npm/dm/@edgeai/edge-client-ts.svg)](https://www.npmjs.com/package/@edgeai/edge-client-ts)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Node.js](https://img.shields.io/badge/node-%E2%89%A520-green.svg)](https://nodejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.5-blue.svg)](https://www.typescriptlang.org/)

**TypeScript edge-client** for the [Edge AI Agent](https://github.com/baphuongna/edge-ai-agent) fleet — a pure-npm re-implementation of the Rust `ec` binary with a **byte-compatible wire protocol**.

A TypeScript edge-client and a Rust edge-client can connect to the **same relay** interchangeably, making `ec-ts` the perfect choice when:

- You want a one-line `npm install -g` install (no Rust toolchain required).
- You are running the edge node on an architecture without a prebuilt `ec` binary.
- You need to embed the client into a Node.js application or a custom daemon.

---

## 🚀 Quick start

```bash
# 1. Install (requires Node.js >= 20)
npm install -g @edgeai/edge-client-ts

# 2. Enroll against your relay.
#    `ec-ts enroll` requires both the operator's API key (from your dashboard)
#    AND the dashboard's admin key (for the relay's oauth-sync gate).
#    First-time enrollment only — re-enroll with the SAME key is
#    rejected by the relay's CRITICAL-1 protection (see "Re-enroll" below).
EDGE_ADMIN_API_KEY=***ADMIN_KEY_FROM_DASHBOARD*** \
  ec-ts enroll --key opk_********************************

# 3. Start the daemon (foreground)
ec-ts run

# Or install it as a system service (auto-start on boot)
ec-ts run --install-service
```

That's it — the daemon will open a WebSocket to the relay, register, and start sending heartbeats.

### Re-enroll

Re-running `ec-ts enroll` with the **same** key returns `403 KEY_FOR_EXISTING_OPERATOR`. The TS client surfaces an actionable hint. Two options:

- **Verify the existing key** — just run `ec-ts run`. The cookie + env file already contain the operator's key.
- **Mint a new key** — use the dashboard's "Rotate API key" button (calls `POST /api/operators/me/api-keys`), then re-enroll with the new key.

---

## 📦 What you get

| Command | Purpose |
|---------|---------|
| `ec-ts run` | Start the daemon (foreground or `--install-service` for systemd/LaunchAgent/schtasks). |
| `ec-ts enroll --key <key>` | Persist a per-operator credential to the OS keychain. |
| `ec-ts whoami` | Print the current operator + relay identity. |
| `ec-ts status` | One-shot health snapshot (WS state, queue depth, last heartbeat). |
| `ec-ts devices` | List devices owned by the current operator. |
| `ec-ts messages` | Tail the message buffer. |

> **Binary name:** `ec-ts` (not `ec`) so you can run both the TypeScript and the Rust clients side-by-side if you want to compare them.

---

## ✅ Protocol parity with the Rust `ec`

The TypeScript client implements the **exact same wire formats** as the Rust client:

- **`/edge` JSON connection** — `register`, `stream`, `ack`, `heartbeat`, `get_config`, `list_agents`, `browser_fetch` message types with identical field names (`machine_id`, `agent_id`, `msg_id`, `type`, `payload`, `timestamp`).
- **`/shell-edge` binary frames** — 17-byte header = 16-byte `session_id` (UUID bytes) + 1-byte `FrameType` + payload. `FrameType` enum values are identical (`Data=0`, `Resize=1`, `Close=2`, …).
- **Buffer dump encryption** — `[KEY_VERSION=1][nonce:12][ciphertext+tag]` AES-256-GCM envelope with keyring rotation.
- **TLS SPKI pinning** — SHA-256 of the DER `SubjectPublicKeyInfo`.
- **`Sec-WebSocket-Protocol`** — `edgeai-v2, <token>[, device-secret=...]`.

A TS edge-client and a Rust edge-client produce **byte-compatible** frames and JSON.

---

## 🔒 Security parity

The TS client implements the same security primitives as the Rust client. Recent security reviews (F-1..F-22, G-1..G-11, H-1..H-9, I-1) closed 36+ findings; key features:

| Primitive | What it does | Toggle |
|-----------|--------------|--------|
| **Buffer encryption** (F-1) | AES-256-GCM at-rest buffer with fail-closed on missing key. | `EDGE_BUFFER_KEY` env |
| **TLS guard** (F-5, F-6) | Refuses plaintext `ws://` in production. Centralized in `cli/http-helpers.ts`. | `NODE_ENV=production` |
| **AGT-03 cmd-gate** (F-12) | Evaluates every tool call against `allowlist` / `always_approve` / `denylist` before forwarding. | `EDGE_CMD_GATE_MODE` |
| **AGT-02 fail-fast** (F-11) | Blocklist for destructive shell commands (e.g. `rm -rf /`). | `EDGE_FAIL_FAST_COMMAND_BLOCKLIST=1` |
| **HMAC sidecar** (F-22, H-3) | `sessions.json.sig` HMAC-SHA256 keyed off `device_secret` with constant-time compare. Auto-migrates pre-G-4 files. | auto |
| **SSRF guard** (F-7) | `browser_fetch` URL must NOT resolve to RFC1918 / loopback / link-local. | auto |
| **URL redaction** (F-9, H-1, I-1) | All error messages run through `redactUrl` (two-pass parser + regex, covers fragments). | auto |
| **Inbound rate-limit** (F-17) | Token bucket on inbound WS frames (50/sec, drops silently when exceeded). | auto |
| **Operator attribution** (G-9, H-7) | Synthetic audit events carry `operator_id` (explicit null when unset). | auto |

**Re-enroll protection:** The relay refuses `api_key_plain` for existing operators (CRITICAL-1). The TS client surfaces an actionable hint (`POST /api/operators/me/api-keys` to mint a new key, or just `ec-ts run` to verify the existing one).

**Deferred items:** see [`docs/security-reviews/`](https://github.com/baphuongna/edge-ai-agent/tree/main/docs/security-reviews) for findings that require relay-side changes (G-7 relay key-mgmt, G-8 DNS rebinding mitigation, I-2 v2 subprotocol).

---

## 📋 Requirements

- **Node.js >= 20** (uses `crypto.randomUUID`, native `fetch`, modern ESM).
- A C++ toolchain for `node-pty` — Microsoft `node-pty` ships **prebuilt `.node` binaries** for common platforms (Linux x64/arm64, macOS x64/arm64, Windows x64), so a toolchain is only needed on unusual architectures.
- The relay server must be reachable via WebSocket (`ws://` for dev, `wss://` for production).

---

## ⚙️ Configuration

Config lives at:

- **Linux:** `~/.config/edge-ai-agent/config.toml`
- **macOS:** `~/Library/Application Support/edge-ai-agent/config.toml`
- **Windows:** `%APPDATA%\edge-ai-agent\config.toml`

A JSON `config.json` is also accepted as a fallback. The schema is identical to the Rust `config.toml` — see [`docs/CONFIGURATION.md`](docs/CONFIGURATION.md) for the full reference.

### Environment variables (preferred for secrets)

> **Never commit credentials to source.** Use environment variables for tokens, API keys, and encryption keys.

| Variable | Purpose |
|----------|---------|
| `EDGE_AUTH_TOKEN` | Fleet shared secret for WS auth (preferred over `config.toml`). |
| `EDGE_ADMIN_API_KEY` | **Required for `ec-ts enroll`**. The dashboard's admin key that gates the relay's `/api/operators/oauth-sync` endpoint. In production, the relay uses `OAUTH_SYNC_ADMIN_KEY` (separate from `ADMIN_API_KEY`); in dev/test, `ADMIN_API_KEY` is accepted as a fallback. |
| `EDGE_BUFFER_KEY` | Buffer-dump AES-256-GCM key (hex, 64 chars = 32 bytes). **Fail-closed**: if unset, the daemon refuses to start. |
| `EDGE_BUFFER_KEY_PREVIOUS` | Previous key for rotation (hex, 64 chars). |
| `EDGE_RELAY_FINGERPRINT` | Pinned TLS SPKI fingerprint (overrides config). |
| `EDGE_OWNER_OPERATOR_ID` | Override the enrolled operator id. |
| `EDGE_OWNER_OPERATOR_KEY` | Set automatically by `enroll` to the value of `--key`. Do not set manually. |
| `EDGEAI_REQUIRE_TLS` | `1` forces `wss://` even outside production. |
| `NODE_ENV=production` | Forces `wss://`. |
| `EDGE_CMD_GATE_MODE` | `off` / `warn` / `block`. AGT-03 cmd-gate; default `block`. |
| `EDGE_CMD_GATE_TIMEOUT_S` | AGT-03 operator-approval timeout (default 60). |
| `EDGE_FAIL_FAST` | `0` / `false` disables AGT-02 output-side fail-fast. |
| `EDGE_FAIL_FAST_COMMAND_BLOCKLIST` | `1` enables AGT-02 layer 2 (command-side blocklist). |

See [`docs/CONFIGURATION.md`](docs/CONFIGURATION.md) for the full env-var reference and precedence rules.

---

## 🛠️ Development

```bash
git clone https://github.com/baphuongna/edge-ai-agent.git
cd edge-ai-agent/edge-client-ts
npm install
npm run typecheck   # tsc --noEmit
npm test            # vitest run
npm run build       # compile to dist/
```

Pre-publish sanity check (mirrors CI):

```bash
npm run prepublishOnly   # typecheck + test + build
```

End-to-end smoke test against a live `ws-service`:

```bash
npm run smoke
```

See [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) for common install/run issues.

---

## 🧱 Architecture (module mapping)

Every module in this package corresponds 1:1 with a Rust module — see
[`docs/PROTOCOL.md`](docs/PROTOCOL.md) for the byte-exact wire spec.

| Rust file                          | TS file                          |
|------------------------------------|----------------------------------|
| `config/settings.rs`               | `src/config/settings.ts`         |
| `config/machine_id.rs`             | `src/config/settings.ts`         |
| `config/device_secret.rs`          | `src/config/settings.ts`         |
| `session/cmd_gate.rs` (config)     | `src/config/cmd-gate.ts`         |
| `network/tls_guard.rs`             | `src/crypto/tls-guard.ts`        |
| `crypto/aes_gcm.rs`                | `src/crypto/aes-gcm.ts`          |
| `logging/file_logger.rs`           | `src/logging/file-logger.ts`     |
| `network/ws_client.rs`             | `src/network/ws-client.ts`       |
| `session/manager.rs`               | `src/session/manager.ts`         |
| `session/shell.rs`                 | `src/session/shell.ts`           |
| `session/shell_frame.rs`           | `src/session/shell-frame.ts`     |
| `session/fail_fast.rs`             | `src/session/fail-fast.ts`       |
| `session/pi_rpc.rs`                | `src/session/pi-rpc.ts`          |
| `session/persistence.rs`           | `src/session/persistence.ts`     |
| `session/sftp.rs`                  | `src/session/sftp.ts`            |
| `buffer/disk_queue.rs`             | `src/buffer/disk-queue.ts`       |
| `cli/mod.rs`                       | `src/cli/index.ts`               |
| `daemon/manager.rs`                | `src/daemon/manager.ts`          |

---

## 📚 Documentation

- [`docs/INSTALLATION.md`](docs/INSTALLATION.md) — Detailed install guide (Linux / macOS / Windows, dev / prod).
- [`docs/CONFIGURATION.md`](docs/CONFIGURATION.md) — Full config schema + env-var precedence.
- [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) — Common errors and fixes.
- [`docs/PROTOCOL.md`](docs/PROTOCOL.md) — Wire-protocol reference (frames, JSON messages, TLS pinning).

---

## 📄 License

MIT — see [`LICENSE`](LICENSE).

This package is part of the Edge AI Agent monorepo. The full system is documented at <https://github.com/baphuongna/edge-ai-agent>.