@loro-dev/loro-repo-engine 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +588 -2
- package/bin/loro-repo.js +6 -0
- package/index.d.ts +144 -0
- package/index.js +38 -0
- package/package.json +48 -3
package/README.md
CHANGED
|
@@ -1,3 +1,589 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@loro-dev/loro-repo-engine`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Prebuilt Node-API (`napi6`) native sync engine & CLI wrapper for **Loro Repo** (`0.1.0`, wire protocol `2`).
|
|
4
|
+
|
|
5
|
+
> **Companion packages**
|
|
6
|
+
> - [`@loro-dev/loro-repo-client`](https://www.npmjs.com/package/@loro-dev/loro-repo-client) — Slim TypeScript IPC SDK (`./node`, `./browser`, host discovery, auto-reconnect, E2EE protectors, auth providers, routing, causal inspection, Roost streams, quiet migrations).
|
|
7
|
+
> - [`@loro-dev/json-patch`](https://www.npmjs.com/package/@loro-dev/json-patch) — Pure-JS deterministic JSON Patch engine (`diff`, `apply`, `compact`), MessagePack/JSON wire codecs, and optional `LoroDoc` bridge (`@loro-dev/json-patch/loro`).
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Table of Contents
|
|
12
|
+
|
|
13
|
+
1. [Role in the 3-Package Stack & Architecture](#1-role-in-the-3-package-stack--architecture)
|
|
14
|
+
2. [Installation & 6-Platform Native Matrix](#2-installation--6-platform-native-matrix)
|
|
15
|
+
3. [5-Minute End-to-End Quick Start](#3-5-minute-end-to-end-quick-start)
|
|
16
|
+
4. [Three Production Deployment Patterns](#4-three-production-deployment-patterns)
|
|
17
|
+
- [Pattern A: Shared Multi-Process Host Election (`ensureEngineHost`)](#pattern-a-shared-multi-process-host-election-ensureenginehost)
|
|
18
|
+
- [Pattern B: Crash-Isolated Electron `utilityProcess` / Child Worker](#pattern-b-crash-isolated-electron-utilityprocess--child-worker)
|
|
19
|
+
- [Pattern C: Standalone Daemon (`loro-repo serve`)](#pattern-c-standalone-daemon-loro-repo-serve)
|
|
20
|
+
5. [Complete Node-API Reference](#5-complete-node-api-reference)
|
|
21
|
+
- [`startEngine(options)` & `idleMs` State Machine](#startengineoptions--idlems-state-machine)
|
|
22
|
+
- [`class Engine`](#class-engine)
|
|
23
|
+
- [`engineVersion()`](#engineversion)
|
|
24
|
+
- [`runCli(args)`](#runcliargs)
|
|
25
|
+
- [Error Contract (`ENGINE_BUSY`, `InvalidArg`, `ENGINE_PROTOCOL_MISMATCH`)](#error-contract)
|
|
26
|
+
6. [On-Disk `<dataDir>` Layout, Security & IPC Wire Specification](#6-on-disk-datadir-layout-security--ipc-wire-specification)
|
|
27
|
+
7. [Complete `loro-repo` CLI & E2EE File Vault Reference](#7-complete-loro-repo-cli--e2ee-file-vault-reference)
|
|
28
|
+
8. [Electron Packaging (`asarUnpack`), Bundlers & macOS Code Signing](#8-electron-packaging-asarunpack-bundlers--macos-code-signing)
|
|
29
|
+
9. [Troubleshooting & Integration FAQ](#9-troubleshooting--integration-faq)
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 1. Role in the 3-Package Stack & Architecture
|
|
34
|
+
|
|
35
|
+
Loro Repo separates heavy local persistence and CRDT execution from lightweight application processes:
|
|
36
|
+
|
|
37
|
+
| Package | Where it runs | Responsibility |
|
|
38
|
+
| :--- | :--- | :--- |
|
|
39
|
+
| **`@loro-dev/loro-repo-engine`** | One host process per `<dataDir>` (Daemon / Electron Main / `utilityProcess` / `loro-repo serve`) | Acquires exclusive `<dataDir>/files.lock`, runs Rust `LoroDoc` / `Flock` / `Meta` / `RoostStream` engines on background Tokio threads, persists per-namespace SQLite WAL databases, seals/opens E2EE frames via reverse-IPC callbacks, drives Durable Streams HTTP/SSE sync, and exposes a private local socket (`0600` UDS / local-only Windows Named Pipe). |
|
|
40
|
+
| **`@loro-dev/loro-repo-client`** | Every JS/TS consumer (Electron Main, Electron Renderer, Web Workers, CLI/Agent processes) | Zero-CRDT RPC & subscription SDK (`RepoClient`). Sends/receives length-prefixed JSON frames over sockets (`./node`) or `MessagePort` (`./browser`), verifies monotonic `txId` visibility via `whenVisible(txId)`, and serves E2EE `seal`/`open` and bearer token reverse-RPCs. |
|
|
41
|
+
| **`@loro-dev/json-patch`** | Any JS/TS runtime (shared dependency of `client`) | Deterministic `diff`, copy-on-write `apply`, `compact`, lossless `bigint`/`Uint8Array` JSON & MessagePack codecs. |
|
|
42
|
+
|
|
43
|
+
```text
|
|
44
|
+
┌──────────────────────────────────────────────────────────────────────────┐
|
|
45
|
+
│ Host Process (Electron Main / Lody Daemon / utilityProcess / CLI serve) │
|
|
46
|
+
│ require("@loro-dev/loro-repo-engine") -> startEngine({ dataDir }) │
|
|
47
|
+
│ │
|
|
48
|
+
│ 1. Acquires `<dataDir>/files.lock` (OS advisory lock; 1 host / dir) │
|
|
49
|
+
│ 2. Binds private local IPC (Unix 0600 socket or Win local-only Pipe) │
|
|
50
|
+
│ Zero TCP listeners (`websocketPort === 0` always) │
|
|
51
|
+
│ 3. Atomically writes `<dataDir>/engine.json` │
|
|
52
|
+
│ 4. Lazily opens `<dataDir>/namespaces/ns_<hex>.sqlite3` (SQLite WAL) │
|
|
53
|
+
└────────────▲────────────────────────▲────────────────────────▲───────────┘
|
|
54
|
+
│ u32be length-prefixed │ │
|
|
55
|
+
│ UTF-8 JSON frames │ │
|
|
56
|
+
┌─────────┴─────────┐ ┌─────────┴──────────┐ ┌─────────┴───────────┐
|
|
57
|
+
│ Electron Main │ │ Electron Renderer │ │ CLI / Agent Worker │
|
|
58
|
+
│ (@loro-dev/ │◄──►│ (@loro-dev/ │ │ (@loro-dev/ │
|
|
59
|
+
│ loro-repo-client │IPC │ loro-repo-client │ │ loro-repo-client │
|
|
60
|
+
│ /node) │brdg│ /browser) │ │ /node) │
|
|
61
|
+
│ + Auth / Keyring │ │ (Zero node:*/Buffer│ │ + Agent Writer │
|
|
62
|
+
└───────────────────┘ └────────────────────┘ └─────────────────────┘
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Why `@loro-dev/loro-repo-engine` deliberately exposes no document API
|
|
66
|
+
|
|
67
|
+
`@loro-dev/loro-repo-engine` exports lifecycle/CLI symbols `startEngine`, `Engine`, `engineVersion`, and `runCli`, plus the in-memory native `ContentKeyring` described below. Document, Flock, Roost, protector registration, and sync APIs live on `RepoClient` in `@loro-dev/loro-repo-client`.
|
|
68
|
+
|
|
69
|
+
This design ensures:
|
|
70
|
+
1. **Uniform multi-process concurrency**: Even the process that called `startEngine` connects to the local socket as an ordinary IPC client, so host and non-host processes share identical ordering, `txId` watermarks, subpath subscriptions, and reverse-RPC routing.
|
|
71
|
+
2. **Single SQLite WAL writer without contention**: Multiple Node/Electron/agent/CLI processes never open the same `.sqlite3` file directly, eliminating SQLite `SQLITE_BUSY` races and duplicate WASM CRDT heaps.
|
|
72
|
+
3. **One binary for Node, Electron & CLI**: `npx loro-repo ...` delegates to `runCli(process.argv.slice(2))` inside the same prebuilt `.node` dynamic library, avoiding a second standalone executable to code-sign or notarize on macOS/Windows.
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## 2. Installation & 6-Platform Native Matrix
|
|
77
|
+
|
|
78
|
+
Install the engine alongside the client SDK:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
pnpm add @loro-dev/loro-repo-engine @loro-dev/loro-repo-client
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`@loro-dev/loro-repo-engine` lists 6 platform packages under `optionalDependencies` with exact version pinning (`0.1.0`). Your package manager installs only the binary matching your host `os` and `cpu`:
|
|
85
|
+
|
|
86
|
+
| Platform package | Rust target triple | OS & Architecture | Runtime C/ABI notes |
|
|
87
|
+
| :--- | :--- | :--- | :--- |
|
|
88
|
+
| `@loro-dev/loro-repo-engine-darwin-arm64` | `aarch64-apple-darwin` | macOS Apple Silicon (M1+) | Uses macOS Security framework for TLS. |
|
|
89
|
+
| `@loro-dev/loro-repo-engine-darwin-x64` | `x86_64-apple-darwin` | macOS Intel x64 | Uses macOS Security framework for TLS. |
|
|
90
|
+
| `@loro-dev/loro-repo-engine-linux-x64-gnu` | `x86_64-unknown-linux-gnu` | Linux x86_64 GNU | Requires **glibc `>= 2.35`** (Ubuntu 22.04+ / Debian 12+). OpenSSL is statically vendored; only `libgcc_s`, `libm`, and `libc` are dynamically linked. |
|
|
91
|
+
| `@loro-dev/loro-repo-engine-linux-arm64-gnu` | `aarch64-unknown-linux-gnu` | Linux ARM64 GNU | Requires **glibc `>= 2.35`**. OpenSSL is statically vendored. |
|
|
92
|
+
| `@loro-dev/loro-repo-engine-win32-x64-msvc` | `x86_64-pc-windows-msvc` | Windows x64 | Built with MSVC; uses Windows SChannel for TLS. |
|
|
93
|
+
| `@loro-dev/loro-repo-engine-win32-arm64-msvc` | `aarch64-pc-windows-msvc` | Windows ARM64 | Built with MSVC; uses Windows SChannel for TLS. |
|
|
94
|
+
|
|
95
|
+
### Runtime Compatibility Guarantees
|
|
96
|
+
|
|
97
|
+
- **Node.js `>= 20` & Electron**: Every native `.node` binary targets **Node-API v6 (`napi6`)**, which is forward-ABI-compatible across all Node.js 20/22/24+ and modern Electron versions. **`node-gyp` and `electron-rebuild` are never needed.**
|
|
98
|
+
- **Alpine / `musl` Linux is NOT supported**: On `linux` without glibc (detected via `process.report.getReport().header.glibcVersionRuntime`), `index.js` throws at load time:
|
|
99
|
+
```text
|
|
100
|
+
@loro-dev/loro-repo-engine has no prebuilt engine for linux-x64 (musl)
|
|
101
|
+
```
|
|
102
|
+
- **Bundled SQLite & Zstd**: `rusqlite` bundles SQLite and `zstd` statically inside `.node` — no host `libsqlite3`, `libssl.so.3`, or `libzstd` installation is needed.
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## 3. 5-Minute End-to-End Quick Start
|
|
107
|
+
|
|
108
|
+
In most Node/Electron Main applications, pair `@loro-dev/loro-repo-engine` with `ensureEngineHost` from `@loro-dev/loro-repo-client/node`:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import * as addon from "@loro-dev/loro-repo-engine";
|
|
112
|
+
import { ensureEngineHost } from "@loro-dev/loro-repo-client/node";
|
|
113
|
+
import { getLodyDocSchemaForId } from "@loro-dev/loro-repo-client/browser";
|
|
114
|
+
|
|
115
|
+
async function main() {
|
|
116
|
+
// 1. Elect this process as host for `dataDir` (or attach as client if another live process already owns it)
|
|
117
|
+
const host = await ensureEngineHost({
|
|
118
|
+
addon,
|
|
119
|
+
dataDir: "/path/to/app-data",
|
|
120
|
+
// Omit `idleMs` for a daemon whose lifetime you control via `host.close()`
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
console.log("Role:", host.role); // "host" | "client"
|
|
124
|
+
console.log("Endpoint:", host.endpoint); // { runId, socket, websocketPort: 0, pid, protocolVersion: 2 }
|
|
125
|
+
|
|
126
|
+
const client = host.client;
|
|
127
|
+
const ns = "workspace-1";
|
|
128
|
+
const room = { kind: "loro_doc", id: "session-1" } as const;
|
|
129
|
+
|
|
130
|
+
// 2. Create (idempotently ensure) a room with a persisted field-level DocSchema
|
|
131
|
+
await client.createRoom(ns, room, "plaintext", {
|
|
132
|
+
docSchema: getLodyDocSchemaForId(room.id),
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// 3. Subscribe to live updates (even a subpath like ["history"])
|
|
136
|
+
const sub = await client.subscribeDoc(ns, room, ["history"], (history, info) => {
|
|
137
|
+
console.log("history updated:", history, "txId:", info.txId, "origin:", info.origin);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// 4. Write structured fields + streaming LoroText splice
|
|
141
|
+
const ack = await client.applyDocPatch(ns, room, [
|
|
142
|
+
{ op: "set", path: ["session"], value: { id: "session-1", status: "running" } },
|
|
143
|
+
{ op: "set", path: ["history"], value: [{ id: "m1", role: "assistant", text: "Hello" }] },
|
|
144
|
+
{ op: "str_splice", path: ["history", 0, "text"], at: 5, del: 0, ins: ", world!" },
|
|
145
|
+
]);
|
|
146
|
+
|
|
147
|
+
// 5. Wait deterministically until the subscription projection reflects our mutation
|
|
148
|
+
await sub.whenVisible(ack.txId);
|
|
149
|
+
|
|
150
|
+
// 6. Read any path on demand
|
|
151
|
+
const snap = await client.readDoc(ns, room);
|
|
152
|
+
console.log("Full document:", snap.value);
|
|
153
|
+
|
|
154
|
+
await sub.unsubscribe();
|
|
155
|
+
// Closes IPC client and, if `host.role === "host"`, gracefully stops the engine & releases `files.lock`
|
|
156
|
+
await host.close();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
main().catch((err) => {
|
|
160
|
+
console.error(err);
|
|
161
|
+
process.exit(1);
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## 4. Three Production Deployment Patterns
|
|
168
|
+
|
|
169
|
+
Because `startEngine` binds to `<dataDir>/files.lock` and `<dataDir>/engine.json`, the exact same package supports three distinct process topologies depending on your reliability and UX requirements.
|
|
170
|
+
|
|
171
|
+
### Pattern A: Shared Multi-Process Host Election (`ensureEngineHost`)
|
|
172
|
+
|
|
173
|
+
Use when multiple peer processes (e.g., Lody Stable, Lody Nightly, background CLI tools, and Electron Main) share one `dataDir`:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
import * as addon from "@loro-dev/loro-repo-engine";
|
|
177
|
+
import { engineVersion } from "@loro-dev/loro-repo-engine";
|
|
178
|
+
import { PROTOCOL_VERSION, ensureEngineHost } from "@loro-dev/loro-repo-client/node";
|
|
179
|
+
|
|
180
|
+
// Verify protocol compatibility before touching shared storage
|
|
181
|
+
if (engineVersion().protocol !== PROTOCOL_VERSION) {
|
|
182
|
+
throw new Error(`Unsupported native engine protocol: ${engineVersion().protocol}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const host = await ensureEngineHost({
|
|
186
|
+
addon,
|
|
187
|
+
dataDir: "/path/to/shared-data",
|
|
188
|
+
handoffTimeoutMs: 5_000, // Retry window if a previous host is exiting or starting up
|
|
189
|
+
clientOptions: {
|
|
190
|
+
autoReconnect: {
|
|
191
|
+
initialDelayMs: 25,
|
|
192
|
+
maxDelayMs: 500,
|
|
193
|
+
timeoutMs: 15_000,
|
|
194
|
+
},
|
|
195
|
+
queueWhileReconnecting: true,
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
How election & handoff work:
|
|
201
|
+
1. `ensureEngineHost` calls `addon.startEngine`. Whoever acquires `<dataDir>/files.lock` first becomes `role: "host"`, publishes `engine.json`, and returns with `host.engine` populated.
|
|
202
|
+
2. Any concurrent process receives an `ENGINE_BUSY` error, immediately reads `engine.json`, checks `protocolVersion === 2`, and connects over the published socket as `role: "client"` (`host.engine === null`).
|
|
203
|
+
3. If the host shuts down cleanly (`host.close()` / `engine.stop()`) or crashes (OS kernel releases `files.lock` immediately on process death), connected clients automatically poll `engine.json` via `reconnectWith`, replay their active subscriptions, `registerProtector`, and `registerAuthProvider` handlers, and continue seamlessly once a new host starts.
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
### Pattern B: Crash-Isolated Electron `utilityProcess` / Child Worker
|
|
208
|
+
|
|
209
|
+
Calling `startEngine` in Electron Main uses the least RAM (no extra Node/V8 runtime), and Rust panics are caught at room mutex boundaries. However, a native abort/segfault/OOM in any `.node` addon terminates its hosting OS process. If you want **hard crash isolation** so a native fault cannot take down Electron Main, spawn `startEngine` in an Electron `utilityProcess` (or `node:child_process` `fork()`):
|
|
210
|
+
|
|
211
|
+
**`engine-worker.ts` (spawned via `utilityProcess.fork` or `child_process.fork`):**
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
import { startEngine } from "@loro-dev/loro-repo-engine";
|
|
215
|
+
|
|
216
|
+
const dataDir = process.argv[2];
|
|
217
|
+
const engine = startEngine({
|
|
218
|
+
dataDir,
|
|
219
|
+
// Optional: stop automatically if all clients disconnect
|
|
220
|
+
idleMs: process.argv.includes("--ephemeral") ? 0 : undefined,
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
// Notify parent (optional — clients can also watch `<dataDir>/engine.json` via `connectEngine`)
|
|
224
|
+
process.parentPort?.postMessage({ type: "ready", endpoint: engine.endpoint });
|
|
225
|
+
|
|
226
|
+
const shutdown = () => {
|
|
227
|
+
engine.stop();
|
|
228
|
+
process.exit(0);
|
|
229
|
+
};
|
|
230
|
+
process.once("SIGTERM", shutdown);
|
|
231
|
+
process.once("SIGINT", shutdown);
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
**`main.ts` (Electron Main connects over local socket using `@loro-dev/loro-repo-client/node`):**
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { utilityProcess } from "electron";
|
|
238
|
+
import { connectEngine } from "@loro-dev/loro-repo-client/node";
|
|
239
|
+
|
|
240
|
+
const worker = utilityProcess.fork(require.resolve("./engine-worker"), [dataDir]);
|
|
241
|
+
const client = await connectEngine(dataDir, {
|
|
242
|
+
waitForEndpointMs: 5_000,
|
|
243
|
+
autoReconnect: true,
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
// If `worker` crashes, respawn it on `worker.once("exit", ...)` — `client`
|
|
247
|
+
// will automatically reconnect to the new `engine.json` socket!
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
### Pattern C: Standalone Daemon (`loro-repo serve`)
|
|
253
|
+
|
|
254
|
+
For language-agnostic orchestration, CLI automation, or integration testing, spawn the bundled `loro-repo` executable (`npx loro-repo serve` or `node <pkg>/bin/loro-repo.js serve`):
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
import { spawn } from "node:child_process";
|
|
258
|
+
import { createRequire } from "node:module";
|
|
259
|
+
import { createInterface } from "node:readline";
|
|
260
|
+
import { connectSocketTransport } from "@loro-dev/loro-repo-client/node";
|
|
261
|
+
import { RepoClient } from "@loro-dev/loro-repo-client";
|
|
262
|
+
|
|
263
|
+
const require = createRequire(import.meta.url);
|
|
264
|
+
const binScript = require.resolve("@loro-dev/loro-repo-engine/bin/loro-repo.js");
|
|
265
|
+
|
|
266
|
+
const child = spawn(process.execPath, [binScript, "serve", "--data-dir", dataDir, "--idle-ms", "5000"], {
|
|
267
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
// `loro-repo serve` prints exactly one single-line JSON readiness payload to stdout when ready:
|
|
271
|
+
const rl = createInterface({ input: child.stdout });
|
|
272
|
+
const firstLine = await new Promise<string>((resolve) => rl.once("line", resolve));
|
|
273
|
+
const endpoint = JSON.parse(firstLine) as {
|
|
274
|
+
run_id: string;
|
|
275
|
+
socket: string;
|
|
276
|
+
websocket_port: number; // always 0
|
|
277
|
+
pid: number;
|
|
278
|
+
protocol_version: number; // 2
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const client = new RepoClient(await connectSocketTransport(endpoint.socket));
|
|
282
|
+
// ... use client ...
|
|
283
|
+
await client.close();
|
|
284
|
+
child.kill("SIGTERM"); // Graceful shutdown; exits with code 0
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
---
|
|
288
|
+
|
|
289
|
+
## 5. Complete Node-API Reference
|
|
290
|
+
|
|
291
|
+
### `startEngine(options)` & `idleMs` State Machine
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
export interface EngineOptions {
|
|
295
|
+
dataDir: string;
|
|
296
|
+
idleMs?: number;
|
|
297
|
+
streamsUrl?: string;
|
|
298
|
+
maxFrameBytes?: number;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function startEngine(options: EngineOptions): Engine;
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
- **Threading & Blocking Behavior**: `startEngine` spawns a dedicated OS thread (`"loro-v2-server"`) hosting a multi-threaded Tokio runtime (`2` worker threads). It **blocks briefly (typically a few milliseconds) until**:
|
|
305
|
+
1. `<dataDir>` exists (created with mode `0700` on Unix),
|
|
306
|
+
2. `<dataDir>/files.lock` is exclusively locked,
|
|
307
|
+
3. the local socket / Windows Named Pipe is bound and listening, and
|
|
308
|
+
4. `<dataDir>/engine.json` has been atomically written and flushed.
|
|
309
|
+
When `startEngine` returns, clients can immediately connect to `engine.endpoint.socket`.
|
|
310
|
+
- **Exact `idleMs` Auto-Shutdown State Machine**:
|
|
311
|
+
Be careful with the distinction between omitted, `0`, and `> 0`:
|
|
312
|
+
1. **`idleMs === undefined` (omitted, default)**: Idle auto-shutdown is **disabled**. The engine runs indefinitely until the host calls `engine.stop()` (or the `Engine` handle is dropped / process receives `SIGTERM`/`SIGINT` in `loro-repo serve`). Recommended for persistent daemons.
|
|
313
|
+
2. **`idleMs === 0`**: **Waits until at least one IPC client connects (`activity_seq > 0`)**, and then stops immediately as soon as active connections return to `0`. It will **not** exit immediately at startup before the first client arrives. Recommended for on-demand background helpers spawned for a single session.
|
|
314
|
+
3. **`idleMs > 0` (e.g., `5000`)**: Starts counting immediately whenever active connections equal `0`. If zero clients connect within `idleMs` ms of startup—or once zero clients remain connected for an uninterrupted `idleMs` ms—the engine automatically exits. Note: Fractional numbers are truncated to integer `u64` milliseconds; `NaN`, `Infinity`, or `< 0` throw an `InvalidArg` error.
|
|
315
|
+
- **`streamsUrl?: string`**: Optional default Durable Streams base URL. Most apps omit this and configure per-namespace remotes explicitly via `client.configureRemote(ns, remote)` (including `encrypted`, `routes`, `shardUrls`, and `aadDomain`). **Important for E2EE**: omitting `streamsUrl` avoids auto-binding a plaintext `"default"` remote to rooms created before `configureRemote` runs.
|
|
316
|
+
- **`maxFrameBytes?: number`**: Maximum allowed IPC frame payload size in bytes (`u32`). Omitting or passing `0` uses the default `67_108_864` (`64 MiB`). Values larger than `67_108_864` are clamped to `64 MiB`. Frame reads or writes exceeding this limit fail closed.
|
|
317
|
+
|
|
318
|
+
### `class Engine`
|
|
319
|
+
|
|
320
|
+
| Member | Type | Exact Behavior |
|
|
321
|
+
| :--- | :--- | :--- |
|
|
322
|
+
| **`endpoint`** (getter) | `EngineEndpoint` | Returns `{ runId, socket, websocketPort, pid, protocolVersion }` matching `<dataDir>/engine.json` (with camelCase property names). `runId` is 32 lowercase hex characters; `websocketPort` is always `0`; `protocolVersion` is `2`. |
|
|
323
|
+
| **`exited`** (getter) | `boolean` | Returns `true` once the engine has exited (due to `stop()`, idle timeout expiration, or unexpected server exit). **Note**: On idle auto-exit, the background server removes `<dataDir>/engine.json` and the Unix socket file and sets `exited = true`, while `<dataDir>/files.lock` remains held until `engine.stop()` is called or the `Engine` object is garbage-collected. Always call `engine.stop()` once you observe `exited === true` if another host may take over `<dataDir>`. |
|
|
324
|
+
| **`stop()`** | `void` | Gracefully shuts down the Tokio runtime, removes `engine.json` and any socket / `/tmp/loro-v2-<runPrefix>` directory, joins the background OS thread, and releases `<dataDir>/files.lock`. **Idempotent** — safe to call multiple times or from shutdown handlers. |
|
|
325
|
+
|
|
326
|
+
### `engineVersion()`
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
export interface EngineVersion {
|
|
330
|
+
package: string; // e.g. "0.1.0"
|
|
331
|
+
protocol: number; // 2
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export function engineVersion(): EngineVersion;
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
Always compare `engineVersion().protocol` (and `<dataDir>/engine.json`'s `protocol_version`) against `PROTOCOL_VERSION` (`2`) from `@loro-dev/loro-repo-client` before attaching to a shared `<dataDir>`.
|
|
338
|
+
|
|
339
|
+
### `runCli(args)`
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
export function runCli(args: string[]): number;
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
Executes the embedded `loro-repo` CLI synchronously in the current process (`args` excludes `argv[0]`, so pass `process.argv.slice(2)`). Returns standard exit codes:
|
|
346
|
+
- `0`: success
|
|
347
|
+
- `1`: runtime or I/O error (including `ENGINE_BUSY` if another daemon already locks `--data-dir`)
|
|
348
|
+
- `2`: invalid CLI usage or bad flags
|
|
349
|
+
|
|
350
|
+
### Error Contract
|
|
351
|
+
|
|
352
|
+
| Condition | Thrown Error / Prefix | Caller Action |
|
|
353
|
+
| :--- | :--- | :--- |
|
|
354
|
+
| Another live process holds `<dataDir>/files.lock` | `Error: ENGINE_BUSY: files.lock is held by another process` | Expected in multi-process setups! Read `<dataDir>/engine.json` and connect as a client (or use `ensureEngineHost`, which handles this automatically). |
|
|
355
|
+
| Negative, `NaN`, or `Infinity` passed as `idleMs` | `TypeError` / N-API `InvalidArg`: `idleMs must be a finite number >= 0` | Pass a non-negative finite integer or `undefined`. |
|
|
356
|
+
| Non-`u32` passed as `maxFrameBytes` | N-API `InvalidArg` | Pass a non-negative 32-bit integer or `undefined`. |
|
|
357
|
+
| Directory permission / socket bind failure | `Error` (`GenericFailure`) with OS I/O details | Ensure parent directory is writable, owned by the current user (`0700` verification fails if owned by another UID), and not corrupted. |
|
|
358
|
+
| Client / host protocol version mismatch (in `client/node`) | `Error: ENGINE_PROTOCOL_MISMATCH: ...` | Prompt user to upgrade the outdated binary/app sharing that `<dataDir>` — do **not** treat `ENGINE_PROTOCOL_MISMATCH` as transient retryable failure. |
|
|
359
|
+
|
|
360
|
+
---
|
|
361
|
+
|
|
362
|
+
## 6. On-Disk `<dataDir>` Layout, Security & IPC Wire Specification
|
|
363
|
+
|
|
364
|
+
Every `<dataDir>` managed by `startEngine` or `loro-repo serve` has the following structure:
|
|
365
|
+
|
|
366
|
+
```text
|
|
367
|
+
<dataDir>/ # Created with mode 0700 on Unix
|
|
368
|
+
├── files.lock # OS advisory lock (flock / LockFileEx); kernel-released on crash/SIGKILL
|
|
369
|
+
├── engine.json # Mode 0600, written atomically via engine.json.tmp + fsync + rename
|
|
370
|
+
├── sock/ # Mode 0700 (Unix only)
|
|
371
|
+
│ └── v2.sock # Mode 0600 Unix domain socket (if total path <= 96 bytes)
|
|
372
|
+
└── namespaces/ # Mode 0700
|
|
373
|
+
└── ns_<hex(utf8(namespace))>.sqlite3 # Single SQLite WAL db per namespace (+ -wal / -shm)
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
### Exact `engine.json` Schema (Disk vs JavaScript)
|
|
377
|
+
|
|
378
|
+
> **Pay close attention to field casing**: `<dataDir>/engine.json` and `loro-repo serve` stdout use **snake_case**, whereas the Node-API `Engine.endpoint` getter and `readEngineEndpoint()` in `@loro-dev/loro-repo-client/node` return **camelCase**.
|
|
379
|
+
|
|
380
|
+
```json
|
|
381
|
+
// On disk (`<dataDir>/engine.json`) & `loro-repo serve` stdout:
|
|
382
|
+
{
|
|
383
|
+
"run_id": "9f2a4b7c1e8d0f3a6b5c4d2e1f0a9b8c",
|
|
384
|
+
"socket": "/path/to/dataDir/sock/v2.sock",
|
|
385
|
+
"websocket_port": 0,
|
|
386
|
+
"pid": 48210,
|
|
387
|
+
"protocol_version": 2
|
|
388
|
+
}
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
| Disk field (`engine.json`) | JS field (`EngineEndpoint`) | Description |
|
|
392
|
+
| :--- | :--- | :--- |
|
|
393
|
+
| `run_id` | `runId` | Random 128-bit lowercase hex instance ID (changes on every host restart). |
|
|
394
|
+
| `socket` | `socket` | Unix domain socket path or Windows Named Pipe (`\\.\pipe\loro-repo-v2-<run_id>`). |
|
|
395
|
+
| `websocket_port` | `websocketPort` | **Always `0`.** Zero TCP/WebSocket ports are ever opened. |
|
|
396
|
+
| `pid` | `pid` | Host OS process ID. |
|
|
397
|
+
| `protocol_version` | `protocolVersion` | Wire protocol version (`2`). |
|
|
398
|
+
|
|
399
|
+
### Unix Socket `SUN_LEN` Fallback & Windows Pipe DACL
|
|
400
|
+
|
|
401
|
+
- **macOS / Linux (`0600` inside `0700`)**: Unix domain sockets fail `bind()` when the path exceeds ~104–108 bytes (`SUN_LEN`). If `<dataDir>/sock/v2.sock` exceeds **96 bytes** (very common inside macOS `/var/folders/...` temp paths or nested `~/Library/Application Support/...` directories), the engine automatically creates an exclusive `0700` directory at **`/tmp/loro-v2-<run_id[..16]>/`** and binds **`/tmp/loro-v2-<run_id[..16]>/v2.sock`** (`0600`), publishing that exact path in `engine.json` and cleaning it up on `stop()`.
|
|
402
|
+
- **Windows (`\\.\pipe\loro-repo-v2-<run_id>`)**: Created with a restrictive security descriptor granting access **only to the current Windows user SID** (`reject_remote_clients(true)` and `first_pipe_instance(true)`).
|
|
403
|
+
|
|
404
|
+
### SQLite WAL Storage Guarantees
|
|
405
|
+
|
|
406
|
+
- Each namespace maps deterministically to `<dataDir>/namespaces/ns_<lowercase_hex_of_utf8_namespace>.sqlite3`.
|
|
407
|
+
- Opened with `PRAGMA journal_mode = WAL`, `PRAGMA synchronous = NORMAL`, and `busy_timeout = 5000ms` (`v2_meta.schema_version = 1`).
|
|
408
|
+
- Unifies `LoroDoc`, `Flock`, `Meta` (`repo-meta`), `RoostStream` (`v2_roost_kv`), room checkpoints, and the single-seal E2EE outbox (`v2_sync_outbox`) in a single ACID SQLite transaction per mutation.
|
|
409
|
+
- Room oplogs automatically compact into snapshots every **`64` operations** (`AUTO_COMPACT_OPLOG_LEN = 64`), or on demand via `client.compactRoom()`.
|
|
410
|
+
- **Local plaintext + zero persisted secrets**: Local SQLite tables store plaintext room state for instant offline cold starts and sub-path queries. E2EE (`LSCE v2 + content-v0`) seals frames exclusively at the cloud outbox boundary (`Unsealed -> Sealed` before upload). **Bearer tokens (`auth_token` / `registerAuthProvider`) are held strictly in RAM and never written to SQLite.** Even if opening a legacy database with an old `auth_token` column, the engine drops the column and truncates the WAL automatically.
|
|
411
|
+
|
|
412
|
+
### IPC Wire Framing
|
|
413
|
+
|
|
414
|
+
Every frame on the local socket is:
|
|
415
|
+
```text
|
|
416
|
+
┌──────────────────────────────┬────────────────────────────────────────┐
|
|
417
|
+
│ length: u32 big-endian (4 B) │ body: UTF-8 JSON (1 .. maxFrameBytes) │
|
|
418
|
+
└──────────────────────────────┴────────────────────────────────────────┘
|
|
419
|
+
```
|
|
420
|
+
Default max body is `64 MiB` (`67_108_864` bytes). Use `LengthPrefixedByteFramer` from `@loro-dev/loro-repo-client` when bridging over custom byte streams.
|
|
421
|
+
|
|
422
|
+
---
|
|
423
|
+
|
|
424
|
+
## 7. Complete `loro-repo` CLI & E2EE File Vault Reference
|
|
425
|
+
|
|
426
|
+
Running `npx loro-repo <subcommand>` (or calling `runCli(args)`) provides both the background server daemon and a Git-style E2EE Markdown/file synchronization vault.
|
|
427
|
+
|
|
428
|
+
### Server & Diagnostics Commands
|
|
429
|
+
|
|
430
|
+
| Command | Description |
|
|
431
|
+
| :--- | :--- |
|
|
432
|
+
| `loro-repo version` or `loro-repo --version` | Prints `{"package":"0.1.0","protocol":2}` to stdout and exits `0`. |
|
|
433
|
+
| `loro-repo serve --data-dir <dir> [--socket <path>] [--streams-url <url>] [--idle-ms <ms>]` | Starts the engine, prints the single-line JSON endpoint to stdout once ready, and runs until `SIGINT`/`SIGTERM` or `idle-ms` expiration. Falls back to `LORO_REPO_STREAMS_URL` env var if `--streams-url` is omitted. |
|
|
434
|
+
|
|
435
|
+
### E2EE File Vault Commands
|
|
436
|
+
|
|
437
|
+
The vault CLI turns any local folder (e.g., an Obsidian vault or workspace docs folder) into a peer-to-peer E2EE workspace backed by Durable Streams + Lody `LSCE v2 + content-v0` + `LVB1` encrypted content-addressed blobs:
|
|
438
|
+
|
|
439
|
+
| Command | Description |
|
|
440
|
+
| :--- | :--- |
|
|
441
|
+
| `loro-repo init [<dir>] --namespace <ns> [--remote <url>] [--bucket <bucket>] [--space <space>] [--key-file <path>] [--plaintext] [--json]` | Initializes `.loro/` (`0700`), creates a new device keyring (`.loro/keyring.json`, `0600`) unless `--plaintext`, optionally writes a portable key bundle to `--key-file`, and configures `origin`. |
|
|
442
|
+
| `loro-repo clone <remote_url> <dir> --namespace <ns> [--bucket <bucket>] [--space <space>] --key-file <path> [--token <tok>] [--plaintext] [--json]` | Installs the exported key bundle (or plaintext mode), pulls from `remote_url`, and checks out the workspace tree into `<dir>`. |
|
|
443
|
+
| `loro-repo status [--vault <dir>] [--json]` | Walks up from cwd to find `.loro/config.json` (unless `--vault` is given) and lists local modified/added/deleted paths vs the last synced base. |
|
|
444
|
+
| `loro-repo sync [--vault <dir>] [--token <tok>] [--json]` | Runs one full bidirectional push + pull + deterministic working-tree reconcile cycle. |
|
|
445
|
+
| `loro-repo watch [--vault <dir>] [--interval-ms <ms>] [--token <tok>] [--json]` | Continuously watches remote streams + local files and syncs (default poll interval `2000` ms) until `SIGINT`/`SIGTERM`. |
|
|
446
|
+
| `loro-repo key export [--vault <dir>] [--out <path>]` | Exports a portable key bundle (`namespace`, `genesis_hex`, epochs, device seed) to stdout or `--out` (`0600`). |
|
|
447
|
+
| `loro-repo key rotate-device [--vault <dir>] [--json]` | Generates a fresh device Ed25519 signing seed (`writer_seed_hex`) for this device and prints its new `pubkey_hex`. |
|
|
448
|
+
| `loro-repo key admit <pubkey_hex> [--vault <dir>]` | Admits another device's `pubkey_hex` into this vault's authorized writers ledger so its E2EE frames are trusted on pull. |
|
|
449
|
+
|
|
450
|
+
**Vault Behavior Details**:
|
|
451
|
+
- **Auth Token Resolution**: Pass `--token <tok>` or set `LORO_REPO_TOKEN` in the environment. Tokens are never written inside `.loro/`.
|
|
452
|
+
- **Root Discovery & `.loroignore`**: When `--vault` is omitted on `status`, `sync`, `watch`, or `key`, the CLI walks ancestor directories until it finds `.loro/config.json`. Put gitignore-style patterns in `<vault>/.loroignore` (e.g., `*.log`, `tmp/`, `!important.log`) to exclude untracked files from `status` and `sync`. Symlinks and `.git`/`.loro` directories are skipped safely; Windows reserved device names (`CON.md`) and path traversals (`..`) are rejected.
|
|
453
|
+
- **Text CRDTs vs Encrypted `LVB1` Blobs**:
|
|
454
|
+
- UTF-8 files `<= 2 MiB` with extensions `.md`, `.markdown`, `.txt`, `.json`, `.canvas`, `.css`, `.yaml`, `.yml`, `.toml`, or `.csv` are stored as `LoroDoc` text documents (`{"text": content}`) and merged cleanly on concurrent edits via CRDT rebase (`str_splice`).
|
|
455
|
+
- All other files (images, PDFs, binaries, non-UTF-8, or files `> 2 MiB`) are deduplicated and split into `256 KiB` encrypted chunks wrapped in `LVB1` records on the `vault-blobs` stream.
|
|
456
|
+
- Unresolvable conflicts write sibling files named `<stem>.conflict-<8hex>.<ext>` instead of silently overwriting data.
|
|
457
|
+
|
|
458
|
+
**CLI Exit Codes**: `0` = success, `1` = runtime / sync / I/O / crypto / `ENGINE_BUSY` error, `2` = invalid subcommand or CLI flag error.
|
|
459
|
+
|
|
460
|
+
---
|
|
461
|
+
|
|
462
|
+
## 8. Electron Packaging (`asarUnpack`), Bundlers & macOS Code Signing
|
|
463
|
+
|
|
464
|
+
### 1. Electron ASAR Unpacking (Required)
|
|
465
|
+
|
|
466
|
+
Electron cannot `dlopen` native `.node` dynamic libraries stored inside an `app.asar` archive. Configure your packager to unpack `@loro-dev/loro-repo-engine` and all its platform packages:
|
|
467
|
+
|
|
468
|
+
**`electron-builder` (`package.json` / `electron-builder.yml`):**
|
|
469
|
+
```json
|
|
470
|
+
{
|
|
471
|
+
"build": {
|
|
472
|
+
"asarUnpack": [
|
|
473
|
+
"**/@loro-dev/loro-repo-engine*/**/*"
|
|
474
|
+
]
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
### 2. Vite / esbuild / Webpack / Rollup Externals
|
|
480
|
+
|
|
481
|
+
Do not try to bundle `.node` binaries or `require("@loro-dev/loro-repo-engine")` with JS bundlers. Mark the package external in your Main / worker bundler config:
|
|
482
|
+
|
|
483
|
+
```ts
|
|
484
|
+
// electron.vite.config.ts / tsup / esbuild / vite
|
|
485
|
+
external: ["@loro-dev/loro-repo-engine", /^@loro-dev\/loro-repo-engine-/]
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
And in your Electron **Renderer**, do **NOT** import `@loro-dev/loro-repo-engine` at all — import `@loro-dev/loro-repo-client/browser` instead!
|
|
489
|
+
|
|
490
|
+
### 3. macOS Code Signing, Hardened Runtime & Notarization
|
|
491
|
+
|
|
492
|
+
Because `.node` files are shared dynamic libraries loaded inside your Electron Main / helper `.app` bundle (rather than standalone Mach-O executables spawned via `execve`), standard `electron-osx-sign` / `@electron/notarize` flows automatically sign and notarize the `.node` binary alongside your app bundle — no separate quarantine stripping or helper executable entitlements are required.
|
|
493
|
+
|
|
494
|
+
---
|
|
495
|
+
|
|
496
|
+
## 9. Troubleshooting & Integration FAQ
|
|
497
|
+
|
|
498
|
+
**Q1: `startEngine` threw `Error: ENGINE_BUSY: files.lock is held by another process`. Is that fatal?**
|
|
499
|
+
No — in multi-process architectures (like Lody Main + CLI + multiple windows), this is normal contention signaling that another process already hosts `dataDir`. Either use `ensureEngineHost` (which catches `ENGINE_BUSY`, reads `engine.json`, and attaches as `role: "client"` automatically) or call `connectEngine(dataDir)`.
|
|
500
|
+
|
|
501
|
+
**Q2: My engine died unexpectedly (`SIGKILL`), will `<dataDir>/files.lock` remain stuck forever?**
|
|
502
|
+
No. `files.lock` uses OS kernel advisory locks (`flock` on Unix, `LockFileEx` on Windows), which the OS kernel releases immediately when the owning process exits or is killed. A stale `engine.json` or `v2.sock` file on disk after a crash is harmless: when the next host acquires `files.lock`, it unlinks the dead socket and atomically replaces `engine.json` via `engine.json.tmp`. Note that after a clean `idleMs` auto-exit where you still hold the `Engine` JS handle, remember to call `engine.stop()` so that handle releases `files.lock`.
|
|
503
|
+
|
|
504
|
+
**Q3: Why is `websocketPort` always `0` in `engine.json` and `Engine.endpoint`?**
|
|
505
|
+
Security. Earlier architectures opened localhost TCP ports that local unprivileged processes or SSRF requests could hit. Loro Repo binds strictly to owner-only (`0600`) Unix domain sockets or current-user-only Windows Named Pipes, with `websocketPort: 0` retained purely as a schema placeholder.
|
|
506
|
+
|
|
507
|
+
**Q4: Why did `endpoint.socket` point to `/tmp/loro-v2-.../v2.sock` instead of inside `dataDir`?**
|
|
508
|
+
On macOS and Linux, Unix domain socket paths have a kernel `SUN_LEN` limit (~104 bytes on macOS, 108 on Linux). When `<dataDir>/sock/v2.sock` exceeds 96 bytes, the engine transparently creates a `0700` directory in `/tmp/loro-v2-<runPrefix>/` and publishes that path in `engine.json` and `engine.endpoint.socket`. Always connect to `endpoint.socket` rather than hardcoding `<dataDir>/sock/v2.sock`.
|
|
509
|
+
|
|
510
|
+
**Q5: Can Electron / Node processes share `dataDir` between a Nightly build and a Stable build?**
|
|
511
|
+
Yes, as long as both report the same `protocolVersion` (`2`). Call `engineVersion().protocol` and let `ensureEngineHost` / `readEngineEndpoint` check `protocol_version === 2`. If a mismatch occurs (`ENGINE_PROTOCOL_MISMATCH`), prompt the user to quit the older process or upgrade rather than corrupting state.
|
|
512
|
+
|
|
513
|
+
**Q6: How do I configure a cloud server without losing end-to-end encryption?**
|
|
514
|
+
Use the native `ContentKeyring` and the `/node` registration adapter below. Omit `streamsUrl` when starting the engine to avoid automatically binding a plaintext default remote.
|
|
515
|
+
|
|
516
|
+
### Native content-v0 keyring
|
|
517
|
+
|
|
518
|
+
`ContentKeyring` delegates cryptography to Rust `LodyKeyringProtector`: HKDF document keys, XChaCha20-Poly1305, strict Ed25519 verification, admitted writer keys, and authenticated room/AAD/snapshot offsets. It returns provider header plus signed content-v0 bytes; the engine owns LSCE framing. Pass reverse-RPC requests unchanged: seal `contextAad` is not open `additionalData`.
|
|
519
|
+
|
|
520
|
+
Save this as `keyring-demo.mjs` after installing the engine and client packages, then run `node keyring-demo.mjs`. It creates a temporary local encrypted-policy room, registers the native protector, and writes a document. It does not contact a remote. The generated keys are disposable demo material; provision and securely retain your workspace genesis, device seed, and epoch keys before using a persistent data directory.
|
|
521
|
+
|
|
522
|
+
```js
|
|
523
|
+
import { randomBytes } from "node:crypto";
|
|
524
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
525
|
+
import { tmpdir } from "node:os";
|
|
526
|
+
import { join } from "node:path";
|
|
527
|
+
import * as addon from "@loro-dev/loro-repo-engine";
|
|
528
|
+
import { ensureEngineHost, contentKeyringRegistration } from "@loro-dev/loro-repo-client/node";
|
|
529
|
+
|
|
530
|
+
const namespace = "keyring-demo";
|
|
531
|
+
const dataDir = await mkdtemp(join(tmpdir(), "loro-keyring-demo-"));
|
|
532
|
+
const keyring = new addon.ContentKeyring();
|
|
533
|
+
const genesis = randomBytes(32);
|
|
534
|
+
const seed = randomBytes(32);
|
|
535
|
+
const epochKey = randomBytes(32);
|
|
536
|
+
keyring.configureNamespace(namespace, genesis);
|
|
537
|
+
const publicKey = keyring.configureWriterSigner(namespace, "member:alice", seed);
|
|
538
|
+
keyring.installEpochKey(namespace, 1, epochKey);
|
|
539
|
+
seed.fill(0);
|
|
540
|
+
epochKey.fill(0);
|
|
541
|
+
const host = await ensureEngineHost({ addon, dataDir });
|
|
542
|
+
try {
|
|
543
|
+
await host.client.registerProtector(contentKeyringRegistration(keyring, {
|
|
544
|
+
domains: [namespace],
|
|
545
|
+
writers: ["member:alice"],
|
|
546
|
+
}));
|
|
547
|
+
const room = { kind: "loro_doc", id: "document" };
|
|
548
|
+
await host.client.createRoom(namespace, room, "encrypted");
|
|
549
|
+
await host.client.applyDocPatch(namespace, room, [
|
|
550
|
+
{ op: "set", path: ["title"], value: "Native E2EE ready" },
|
|
551
|
+
], "member:alice");
|
|
552
|
+
console.log((await host.client.readDoc(namespace, room)).value);
|
|
553
|
+
} finally {
|
|
554
|
+
await host.close();
|
|
555
|
+
keyring.clearNamespace(namespace);
|
|
556
|
+
await rm(dataDir, { recursive: true, force: true });
|
|
557
|
+
}
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
For cloud sync, register the protector first, then configure `{ remote_id: "cloud", base_url: yourStreamsUrl, encrypted: true }` with `client.configureRemote(namespace, remote)` and call `client.syncNamespace(namespace, "cloud")`. Configure bearer auth separately if the server requires it. A peer needs the same genesis and epoch keys plus `admitWriterPubkey(namespace, publicKey)` for every trusted sending device. Only admit keys authenticated by your application's verified ledger. This keyring does not fetch or verify that ledger or distribute keys.
|
|
561
|
+
|
|
562
|
+
All genesis/seed/key/public-key arguments are exactly 32-byte `Uint8Array`s. Epochs are integers from `0` through `4294967295`. Namespace and writer names are nonempty and cannot contain NUL. `configureNamespace` rejects conflicting genesis; `installEpochKey` permits identical reinstalls and rejects conflicting material for an existing epoch. The highest installed epoch immediately becomes the seal epoch. Older installed epochs remain usable for opening history.
|
|
563
|
+
|
|
564
|
+
`configureNamespace(namespace, genesis, seed?)` installs an optional default signer. `configureWriterSigner(namespace, writer, seed)` installs a concrete writer signer; a requested writer never falls back to the default. Both return the signer's public key and admit it locally. Replacing a signer does not revoke the previous public key: explicitly call `revokeWriterPubkey` when your authorization policy requires it. Revocation blocks both opening that writer's frames and sealing with its local signer. `clearNamespace` drops all namespace custody and admission; restore genesis, trusted writers, and required epochs before resuming sync.
|
|
565
|
+
|
|
566
|
+
Custody exists only in the Node process holding the keyring, independently of which process hosts the engine. Rust keeps custody copies; clear caller-owned mutable seed/key buffers after installation. Keys are never sent through the adapter's IPC registration. `contentKeyringRegistration` converts native failures into sanitized `ProtectError`s (`missing_provider`, `unknown_key`, `unauthorized`, `invalid_frame`), retaining the engine's retry/hold classification without copying native error details. For a reader-only connection use `{ domains: [namespace], readOnly: true }`. The adapter is exported only from `/node`; browser renderers do not load the native keyring.
|
|
567
|
+
|
|
568
|
+
`seal` and `open` are synchronous native calls and occupy the calling Node thread. For large snapshots or frequent encryption, keep custody and its client connection in a dedicated worker/utility process so Electron Main remains responsive. Instantiate and provision the keyring in that process; the native keyring object is not transferred through a renderer bridge. Encryption here protects remote replication; local SQLite document storage remains plaintext.
|
|
569
|
+
|
|
570
|
+
### Rotation barrier and executable checks
|
|
571
|
+
|
|
572
|
+
For every affected remote, retain the complete existing remote config and use this order:
|
|
573
|
+
|
|
574
|
+
1. `await client.configureRemote(namespace, { ...remote, paused: true })`.
|
|
575
|
+
2. `await client.syncNamespace(namespace, remote.remote_id)`. The namespace sync lock waits for prior sync work; a seal callback completing while paused has its result discarded. Paused sync drains already sealed rows, holds unsealed rows, and skips pull. Check status for blocked or still-sealed rows and resolve drain failures before advancing.
|
|
576
|
+
3. While still paused, install the new epoch in every reader and writer process and await explicit acknowledgements from all participants. Coordinate concurrent configuration changes so another process cannot resume the remote early. A failed or missing acknowledgement leaves the remote paused.
|
|
577
|
+
4. `await client.configureRemote(namespace, { ...remote, paused: false })`, then `await client.syncNamespace(namespace, remote.remote_id)`. Held plaintext is now sealed using the new epoch. Retain old epoch keys for historical frames and presealed retries.
|
|
578
|
+
|
|
579
|
+
Pausing is per remote; repeat the barrier for all affected remotes before changing shared namespace custody. Reconnect replays the registration using the same keyring object, but a process restart requires secure custody restoration. No new engine protocol or automatic distributed coordinator is introduced.
|
|
580
|
+
|
|
581
|
+
Repository verification commands (run from `rust/`, after building the addon for your platform):
|
|
582
|
+
|
|
583
|
+
```sh
|
|
584
|
+
cargo build -p loro-repo-crypto --example native_keyring_interop
|
|
585
|
+
node npm/engine/keyring-smoke.mjs
|
|
586
|
+
pnpm --dir packages/client exec vitest run test/keyring.test.ts test/keyring-interop.test.ts test/keyring-e2e.test.ts
|
|
587
|
+
```
|
|
588
|
+
|
|
589
|
+
`keyring-smoke.mjs` exchanges update and snapshot fixtures in both directions with a separate Rust executable, checks unknown epochs, unauthorized/revoked writers, tampering, AAD/room/offset mismatches, immutable key conflicts, and clear/restore/history behavior. Set `KEYRING_INTEROP_BIN` to override the fixture executable path. The interop test also exchanges frames with an independent TypeScript test implementation. The E2E tests require a built `loro-repo` daemon (`LORO_REPO_BIN` override supported) and use real IPC, HTTP, and native custody. They cover a held seal callback plus separate custody processes, lost and stale installation acknowledgements, crash/restart, restoration of historical keys, and epoch-2 writes after all live participants acknowledge. These checks exercise an application coordinator in a test harness; production key delivery and coordinator recovery remain application responsibilities.
|
package/bin/loro-repo.js
ADDED
package/index.d.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/** Options for {@link startEngine}. */
|
|
2
|
+
export interface EngineOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Directory holding `<dataDir>/files.lock`, `<dataDir>/engine.json`, and
|
|
5
|
+
* per-namespace SQLite WAL databases (`<dataDir>/namespaces/ns_<hex>.sqlite3`).
|
|
6
|
+
*/
|
|
7
|
+
dataDir: string;
|
|
8
|
+
/**
|
|
9
|
+
* Idle auto-shutdown timeout in milliseconds when zero IPC clients are connected.
|
|
10
|
+
*
|
|
11
|
+
* - `undefined` (omitted): never auto-stops; the host owns the engine lifetime and calls `stop()`.
|
|
12
|
+
* - `0`: waits until the **first** IPC client connects, then stops immediately once the last client closes.
|
|
13
|
+
* - `> 0`: stops after `idleMs` ms with zero active connections (after at least one client has connected, or on idle wait depending on host lifecycle).
|
|
14
|
+
*/
|
|
15
|
+
idleMs?: number;
|
|
16
|
+
/** Default Durable Streams base URL used when a remote omits an explicit base URL. */
|
|
17
|
+
streamsUrl?: string;
|
|
18
|
+
/** Maximum local IPC frame size in bytes (omitted uses `67_108_864` / `64 MiB`). */
|
|
19
|
+
maxFrameBytes?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Runtime IPC endpoint published by a running engine.
|
|
24
|
+
* Clients read `<dataDir>/engine.json` (which uses snake_case keys on disk) via
|
|
25
|
+
* `readEngineEndpoint` and connect with `@loro-dev/loro-repo-client/node`.
|
|
26
|
+
*/
|
|
27
|
+
export interface EngineEndpoint {
|
|
28
|
+
/** Unique 32-character lowercase hex identifier for this host engine instance. */
|
|
29
|
+
runId: string;
|
|
30
|
+
/** Local IPC address: `0600` Unix domain socket path on macOS/Linux, or `\\.\pipe\loro-repo-v2-<runId>` on Windows. */
|
|
31
|
+
socket: string;
|
|
32
|
+
/** Always `0`. No local TCP or WebSocket port is ever opened; kept for legacy reader compatibility. */
|
|
33
|
+
websocketPort: number;
|
|
34
|
+
/** OS process ID of the process hosting this engine. */
|
|
35
|
+
pid: number;
|
|
36
|
+
/** Wire protocol version implemented by this engine (currently `2`). */
|
|
37
|
+
protocolVersion: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Running in-process engine handle returned by {@link startEngine}. */
|
|
41
|
+
export declare class Engine {
|
|
42
|
+
/** Published local IPC endpoint matching `<dataDir>/engine.json`. */
|
|
43
|
+
get endpoint(): EngineEndpoint;
|
|
44
|
+
/** `true` once the engine has exited (via `stop()`, idle timeout, or lock loss). */
|
|
45
|
+
get exited(): boolean;
|
|
46
|
+
/** Gracefully stops the engine, removes `engine.json` + local socket, and waits for background threads. Idempotent. */
|
|
47
|
+
stop(): void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Starts the persistent Rust sync engine for `options.dataDir` on a background thread of this process.
|
|
52
|
+
*
|
|
53
|
+
* Acquires `<dataDir>/files.lock`, opens per-namespace SQLite WAL files lazily, binds a private
|
|
54
|
+
* Unix socket (`0600`, falling back to `/tmp/loro-v2-<runPrefix>/v2.sock` if `<dataDir>/sock/v2.sock` exceeds 96 bytes)
|
|
55
|
+
* or local-only Windows Named Pipe, and atomically writes `<dataDir>/engine.json` before returning.
|
|
56
|
+
*
|
|
57
|
+
* @throws Throws an `Error` whose message starts with `"ENGINE_BUSY"` if another live process already holds `files.lock`.
|
|
58
|
+
* Callers should read `<dataDir>/engine.json` (or use `ensureEngineHost` from `@loro-dev/loro-repo-client/node`) and connect as a client.
|
|
59
|
+
*/
|
|
60
|
+
export declare function startEngine(options: EngineOptions): Engine;
|
|
61
|
+
|
|
62
|
+
/** Package & wire-protocol version descriptor returned by {@link engineVersion}. */
|
|
63
|
+
export interface EngineVersion {
|
|
64
|
+
/** Semantic version of this native package (e.g. `"0.1.0"`). */
|
|
65
|
+
package: string;
|
|
66
|
+
/** Wire protocol version supported by this engine (`2`). */
|
|
67
|
+
protocol: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Returns the engine's package version and wire protocol version before touching a `dataDir`. */
|
|
71
|
+
export declare function engineVersion(): EngineVersion;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Runs the bundled `loro-repo` CLI in-process.
|
|
75
|
+
*
|
|
76
|
+
* Supports `version`, `serve --data-dir <dir> [--socket <path>] [--streams-url <url>] [--idle-ms <ms>]`,
|
|
77
|
+
* and E2EE vault commands (`init`, `clone`, `status`, `sync`, `watch`, `key export|rotate-device|admit`).
|
|
78
|
+
*
|
|
79
|
+
* @param args CLI arguments excluding `argv[0]` (`process.argv.slice(2)`).
|
|
80
|
+
* @returns Process exit code (`0` success, `1` runtime error, `2` CLI usage error).
|
|
81
|
+
*/
|
|
82
|
+
export declare function runCli(args: string[]): number;
|
|
83
|
+
|
|
84
|
+
/** Engine-provided request; pass bytes through without re-encoding or wrapping LSCE. */
|
|
85
|
+
export interface ContentSealRequest {
|
|
86
|
+
namespace: string;
|
|
87
|
+
room: { kind: "loro_doc" | "flock" | "meta" | "roost_stream"; id: string };
|
|
88
|
+
payloadKind: "update_batch" | "snapshot";
|
|
89
|
+
writer?: string | null;
|
|
90
|
+
continuationOffset?: string | null;
|
|
91
|
+
contextAad: Uint8Array;
|
|
92
|
+
plaintext: Uint8Array;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Complete open AAD differs from seal contextAad; use the engine-provided value. */
|
|
96
|
+
export interface ContentOpenRequest {
|
|
97
|
+
namespace: string;
|
|
98
|
+
room: ContentSealRequest["room"];
|
|
99
|
+
payloadKind: ContentSealRequest["payloadKind"];
|
|
100
|
+
continuationOffset?: string | null;
|
|
101
|
+
header: Uint8Array;
|
|
102
|
+
sealed: Uint8Array;
|
|
103
|
+
additionalData: Uint8Array;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Signed content-v0 payload and provider header; the engine supplies outer LSCE framing. */
|
|
107
|
+
export interface ContentSealResult {
|
|
108
|
+
header: Uint8Array;
|
|
109
|
+
sealed: Uint8Array;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Native Rust Lody content-v0 key custody, scoped to this Node process.
|
|
114
|
+
* Keys/genesis/seeds/public keys must be exactly 32 bytes. Names must be nonempty.
|
|
115
|
+
* No persistence, key distribution, ledger verification, or cross-process rotation barrier is provided.
|
|
116
|
+
* Only admit public keys after your application verifies their authorization.
|
|
117
|
+
* Rust holds custody copies; callers must erase their own mutable seed/key buffers after installation.
|
|
118
|
+
* Failures use fixed messages `CONTENT_KEYRING:<kind>` with no request or secret data,
|
|
119
|
+
* where kind is missing_provider, unknown_key, unauthorized, or invalid_frame.
|
|
120
|
+
* Malformed JavaScript argument types can also throw NAPI TypeErrors.
|
|
121
|
+
*/
|
|
122
|
+
export declare class ContentKeyring {
|
|
123
|
+
constructor();
|
|
124
|
+
/** Set immutable namespace genesis; optional default signer is admitted and replaces the prior default. */
|
|
125
|
+
configureNamespace(namespace: string, genesis: Uint8Array, signerSeed?: Uint8Array | null): Uint8Array | null;
|
|
126
|
+
/** Install/replace an explicit writer signer and admit its public key; does not revoke the old key. */
|
|
127
|
+
configureWriterSigner(namespace: string, writer: string, signerSeed: Uint8Array): Uint8Array;
|
|
128
|
+
/** Admit a validated Ed25519 key. Authorization must come from a trusted application ledger. */
|
|
129
|
+
admitWriterPubkey(namespace: string, publicKey: Uint8Array): void;
|
|
130
|
+
/** Remove admission (including local sealing permission); idempotent, does not erase signer custody. */
|
|
131
|
+
revokeWriterPubkey(namespace: string, publicKey: Uint8Array): void;
|
|
132
|
+
/**
|
|
133
|
+
* Install an integer epoch in [0, 4294967295]. Highest installed epoch immediately seals new data.
|
|
134
|
+
* Identical reinstall is allowed; a conflicting key for an existing epoch is rejected.
|
|
135
|
+
* Retain older epochs for historical ciphertext; install only after readers are ready.
|
|
136
|
+
*/
|
|
137
|
+
installEpochKey(namespace: string, epoch: number, key: Uint8Array): void;
|
|
138
|
+
/** Drop all namespace custody and admission; idempotent. Subsequent seal/open reports missing_provider. */
|
|
139
|
+
clearNamespace(namespace: string): void;
|
|
140
|
+
/** Synchronous native seal; explicit writer never falls back to the default signer. Roost streams unsupported. */
|
|
141
|
+
seal(request: ContentSealRequest): ContentSealResult;
|
|
142
|
+
/** Strict signature, admission, epoch, AAD and snapshot-offset verification before returning plaintext. */
|
|
143
|
+
open(request: ContentOpenRequest): Uint8Array;
|
|
144
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Loads the prebuilt addon for this platform: a local build next to this file
|
|
2
|
+
// (development, CI before packaging), else the platform package npm installed
|
|
3
|
+
// as an optional dependency. See rust/docs/engine-distribution.md.
|
|
4
|
+
"use strict";
|
|
5
|
+
|
|
6
|
+
const { existsSync } = require("node:fs");
|
|
7
|
+
const { join } = require("node:path");
|
|
8
|
+
|
|
9
|
+
const TARGETS = {
|
|
10
|
+
"darwin-arm64": "darwin-arm64",
|
|
11
|
+
"darwin-x64": "darwin-x64",
|
|
12
|
+
"linux-x64": "linux-x64-gnu",
|
|
13
|
+
"linux-arm64": "linux-arm64-gnu",
|
|
14
|
+
"win32-x64": "win32-x64-msvc",
|
|
15
|
+
"win32-arm64": "win32-arm64-msvc",
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function isMusl() {
|
|
19
|
+
if (process.platform !== "linux") return false;
|
|
20
|
+
const report = typeof process.report?.getReport === "function" ? process.report.getReport() : null;
|
|
21
|
+
return !report?.header?.glibcVersionRuntime;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function load() {
|
|
25
|
+
const key = `${process.platform}-${process.arch}`;
|
|
26
|
+
const suffix = TARGETS[key];
|
|
27
|
+
if (!suffix || isMusl()) {
|
|
28
|
+
throw new Error(
|
|
29
|
+
`@loro-dev/loro-repo-engine has no prebuilt engine for ${key}${isMusl() ? " (musl)" : ""}`,
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
const local = join(__dirname, `loro-repo-engine.${suffix}.node`);
|
|
33
|
+
if (existsSync(local)) return require(local);
|
|
34
|
+
return require(`@loro-dev/loro-repo-engine-${suffix}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const { Engine, ContentKeyring, startEngine, engineVersion, runCli } = load();
|
|
38
|
+
module.exports = { Engine, ContentKeyring, startEngine, engineVersion, runCli };
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@loro-dev/loro-repo-engine",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The loro-repo engine, prebuilt as a Node-API addon. Source is not public (D3).",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"main": "index.js",
|
|
10
|
+
"types": "index.d.ts",
|
|
11
|
+
"bin": {
|
|
12
|
+
"loro-repo": "./bin/loro-repo.js"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"index.js",
|
|
16
|
+
"index.d.ts",
|
|
17
|
+
"bin"
|
|
18
|
+
],
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">= 20"
|
|
21
|
+
},
|
|
22
|
+
"napi": {
|
|
23
|
+
"binaryName": "loro-repo-engine",
|
|
24
|
+
"packageName": "@loro-dev/loro-repo-engine",
|
|
25
|
+
"targets": [
|
|
26
|
+
"aarch64-apple-darwin",
|
|
27
|
+
"x86_64-apple-darwin",
|
|
28
|
+
"x86_64-unknown-linux-gnu",
|
|
29
|
+
"aarch64-unknown-linux-gnu",
|
|
30
|
+
"x86_64-pc-windows-msvc",
|
|
31
|
+
"aarch64-pc-windows-msvc"
|
|
32
|
+
]
|
|
33
|
+
},
|
|
34
|
+
"optionalDependencies": {
|
|
35
|
+
"@loro-dev/loro-repo-engine-darwin-arm64": "0.1.0",
|
|
36
|
+
"@loro-dev/loro-repo-engine-darwin-x64": "0.1.0",
|
|
37
|
+
"@loro-dev/loro-repo-engine-linux-x64-gnu": "0.1.0",
|
|
38
|
+
"@loro-dev/loro-repo-engine-linux-arm64-gnu": "0.1.0",
|
|
39
|
+
"@loro-dev/loro-repo-engine-win32-x64-msvc": "0.1.0",
|
|
40
|
+
"@loro-dev/loro-repo-engine-win32-arm64-msvc": "0.1.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@napi-rs/cli": "^3.10.0"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "napi build --platform --no-js --dts napi.generated.d.ts --release --manifest-path Cargo.toml --output-dir .",
|
|
47
|
+
"build:debug": "napi build --platform --no-js --dts napi.generated.d.ts --manifest-path Cargo.toml --output-dir .",
|
|
48
|
+
"artifacts": "napi artifacts --output-dir artifacts --npm-dir npm",
|
|
49
|
+
"smoke": "node smoke.mjs"
|
|
50
|
+
}
|
|
6
51
|
}
|