Skip to content

Commit e6a8feb

Browse files
authored
refactor(pairing): move device pairing store to shared SQLite state DB (#103160)
* refactor(pairing): move device pairing store to shared SQLite state DB Device pairing, pending requests, and bootstrap tokens now live in the device_pairing_* / device_bootstrap_tokens tables of state/openclaw.sqlite instead of devices/{paired,pending,bootstrap}.json. Gateways import legacy paired records once at startup (before the node-surface fold) and archive the JSON files with a .migrated suffix; transient pending/bootstrap rows are dropped. The unshipped node_pairing_* tables are removed from the schema and dropped from existing DBs. Doctor now flags un-imported legacy store files instead of corrupt-JSON reads. * refactor(pairing): drop stale awaits now that store persistence is synchronous * refactor(pairing): extract leaf record types to break store/domain module cycle
1 parent b0e77bb commit e6a8feb

25 files changed

Lines changed: 1056 additions & 804 deletions

‎docs/channels/pairing.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ openclaw devices reject <requestId>
183183
When an explicit approval is denied because the approving paired-device session
184184
was opened with pairing-only scope, the CLI retries the same request with
185185
`operator.admin`. This lets an existing admin-capable paired device recover a new
186-
Control UI/browser pairing without editing `devices/paired.json` by hand. The
186+
Control UI/browser pairing without editing the pairing store by hand. The
187187
Gateway still validates the retried connection; tokens that cannot authenticate
188188
with `operator.admin` remain blocked.
189189

@@ -219,10 +219,13 @@ approval.
219219

220220
### Node pairing state storage
221221

222-
Stored under `~/.openclaw/devices/`:
222+
Stored in the shared SQLite state database at `~/.openclaw/state/openclaw.sqlite`:
223223

224-
- `pending.json` (short-lived; pending requests expire after 5 minutes)
225-
- `paired.json` (paired devices + tokens)
224+
- pending device pairing requests (short-lived; they expire after 5 minutes)
225+
- paired devices + tokens
226+
227+
Older gateways kept this state in `~/.openclaw/devices/*.json`; those files are
228+
imported into SQLite at gateway startup and archived with a `.migrated` suffix.
226229

227230
### Notes
228231

‎docs/gateway/pairing.md‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ read_when:
77
title: "Node pairing"
88
---
99

10-
Node pairing has two layers, both stored on the paired device record in
11-
`devices/paired.json`:
10+
Node pairing has two layers, both stored on the paired device record in the
11+
Gateway's SQLite state database:
1212

1313
- **Device pairing** (role `node`) gates the `connect` handshake. See
1414
[Trusted-CIDR device auto-approval](#trusted-cidr-device-auto-approval)
@@ -65,7 +65,7 @@ Methods:
6565
- `node.pair.approve` - approve a pending request.
6666
- `node.pair.reject` - reject a pending request.
6767
- `node.pair.remove` - remove a paired node. This revokes the device's `node`
68-
role in `devices/paired.json`, drops the approved node surface with it, and
68+
role in the paired-device store, drops the approved node surface with it, and
6969
invalidates/disconnects that device's node-role sessions. A **mixed-role**
7070
device (for example one that also holds `operator`) keeps its row and only
7171
loses the `node` role; a node-only device row is deleted. Authz:
@@ -245,20 +245,20 @@ operator auth.
245245

246246
## Storage (local, private)
247247

248-
Pairing state lives on the paired device records under the Gateway state
249-
directory (default `~/.openclaw`):
248+
Pairing state lives on the paired device records in the shared SQLite state
249+
database under the Gateway state directory (default `~/.openclaw`):
250250

251-
- `~/.openclaw/devices/paired.json` (device auth, approved node surfaces, and
252-
pending surface requests)
253-
- `~/.openclaw/devices/pending.json` (pending device pairing requests)
251+
- `~/.openclaw/state/openclaw.sqlite` (paired devices with device auth,
252+
approved node surfaces, pending surface requests, pending device pairing
253+
requests, and bootstrap tokens)
254254

255-
If you override `OPENCLAW_STATE_DIR`, the `devices/` folder moves with it.
256-
Gateways upgraded from releases with the standalone `nodes/` store fold those
257-
rows in at startup and leave `nodes/*.json.migrated` archives behind.
255+
If you override `OPENCLAW_STATE_DIR`, the database moves with it. Gateways
256+
upgraded from releases with JSON stores import them at startup and leave
257+
`devices/*.json.migrated` and `nodes/*.json.migrated` archives behind.
258258

259259
Security notes:
260260

261-
- Device tokens are secrets; treat `paired.json` as sensitive.
261+
- Device tokens are secrets; treat the state database as sensitive.
262262
- Rotating a device token uses `openclaw devices rotate` /
263263
`device.token.rotate`.
264264

‎docs/nodes/index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Pending pairing requests expire 5 minutes after the device's last retry — a de
3434
- `nodes status` marks a node as **paired** when its device pairing role includes `node`.
3535
- The device pairing record is the durable approved-role contract. Token rotation stays inside that contract; it cannot upgrade a paired node into a role that pairing approval never granted.
3636
- `node.pair.*` (CLI: `openclaw nodes pending/approve/reject/remove/rename`) is a separate, gateway-owned node pairing store that tracks the node's approved command/capability surface across reconnects. It does **not** gate transport authentication — device pairing does that.
37-
- `openclaw nodes remove --node <id|name|ip>` removes a node pairing. For a device-backed node it revokes the device's `node` role in `devices/paired.json` and disconnects that device's node-role sessions: a mixed-role device keeps its row and only loses the `node` role, while a node-only device row is deleted. It also clears any matching entry from the separate node pairing store. `operator.pairing` may remove non-operator node rows on other devices; a device-token caller revoking its own node role on a mixed-role device additionally needs `operator.admin`.
37+
- `openclaw nodes remove --node <id|name|ip>` removes a node pairing. For a device-backed node it revokes the device's `node` role in the paired-device store and disconnects that device's node-role sessions: a mixed-role device keeps its row and only loses the `node` role, while a node-only device row is deleted. It also clears any matching entry from the separate node pairing store. `operator.pairing` may remove non-operator node rows on other devices; a device-token caller revoking its own node role on a mixed-role device additionally needs `operator.admin`.
3838
- Approval scope follows the pending request's declared commands:
3939
- commandless request: `operator.pairing`
4040
- non-exec node commands: `operator.pairing` + `operator.write`

‎docs/refactor/database-first.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2143,10 +2143,11 @@ Add a repo check that fails new runtime writes to legacy state paths:
21432143
- `cron/jobs.json`
21442144
- `jobs-state.json`
21452145
- `device-pair-notify.json`
2146-
- `devices/pending.json`
2147-
- `devices/paired.json`
2148-
- `devices/bootstrap.json`
2149-
- `nodes/pending.json` / `nodes/paired.json` (retired 2026.7: folded into `devices/paired.json` at gateway startup)
2146+
- `devices/pending.json` / `devices/paired.json` / `devices/bootstrap.json`
2147+
(retired 2026.7: runtime store is `device_pairing_*` /
2148+
`device_bootstrap_tokens` in the shared state DB; paired records import at
2149+
gateway startup, transient pending/bootstrap rows are dropped)
2150+
- `nodes/pending.json` / `nodes/paired.json` (retired 2026.7: folded into paired device records at gateway startup)
21502151
- `identity/device.json`
21512152
- `identity/device-auth.json`
21522153
- `push/web-push-subscriptions.json`

‎src/commands/doctor-device-pairing.test.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ describe("noteDevicePairingHealth", () => {
155155
});
156156
});
157157

158-
it("warns when local pairing state is corrupt instead of treating it as empty", async () => {
158+
it("warns when a legacy pairing store file has not been imported into SQLite", async () => {
159159
await withTempDir("openclaw-doctor-device-pairing-", async (stateDir) => {
160160
await withEnvAsync(
161161
{
@@ -176,7 +176,7 @@ describe("noteDevicePairingHealth", () => {
176176
const message = requireNoteMessage();
177177
expect(requireNoteTitle()).toBe("Device pairing");
178178
expect(message).toContain("paired.json");
179-
expect(message).toContain("refused to treat it as empty");
179+
expect(message).toContain("has not been imported");
180180
expect(await fs.readFile(pairedPath, "utf8")).toBe("{not-json}");
181181

182182
const findings = await collectDevicePairingHealthFindings({
@@ -186,9 +186,9 @@ describe("noteDevicePairingHealth", () => {
186186
expect.objectContaining({
187187
checkId: "core/doctor/device-pairing",
188188
severity: "warning",
189-
path: pairedPath,
190-
requirement: "pairing-store-parse",
191-
message: expect.stringContaining("refused to treat it as empty"),
189+
path: "devices.legacy-store",
190+
requirement: "pairing-store-legacy-file",
191+
message: expect.stringContaining("has not been imported"),
192192
}),
193193
]);
194194
expect(await fs.readFile(pairedPath, "utf8")).toBe("{not-json}");

‎src/commands/doctor-device-pairing.ts‎

Lines changed: 42 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
type DevicePairingPendingRequest,
1818
type PairedDevice,
1919
} from "../infra/device-pairing.js";
20-
import { JsonFileReadError, tryReadJsonSync } from "../infra/json-files.js";
20+
import { tryReadJsonSync } from "../infra/json-files.js";
2121
import type { DeviceAuthStore } from "../shared/device-auth.js";
2222
import { normalizeDeviceAuthScopes } from "../shared/device-auth.js";
2323
import { roleScopesAllow } from "../shared/operator-scope-compat.js";
@@ -537,9 +537,19 @@ function formatLocalDeviceAuthIssue(issue: LocalDeviceAuthIssue): string {
537537
return `- ${issue.message}`;
538538
}
539539

540-
function formatPairingStoreReadIssue(error: JsonFileReadError): string {
541-
const problem = error.reason === "parse" ? "contains invalid JSON" : "could not be read";
542-
return `- Device pairing store ${error.filePath} ${problem}. OpenClaw refused to treat it as empty to avoid overwriting approved pairings. Fix the JSON or file permissions, or move it aside and re-pair devices.`;
540+
function formatLegacyPairingStoreIssue(filePath: string): string {
541+
return `- Legacy device pairing store ${filePath} has not been imported into the SQLite state store yet. The gateway imports and archives it at startup, so restart the gateway. If the file persists across restarts it is likely unreadable; OpenClaw refused to treat it as empty to avoid dropping approved pairings, so fix or move it aside, then restart.`;
542+
}
543+
544+
/** Warn about legacy devices/*.json files the startup SQLite import has not archived. */
545+
async function collectLegacyPairingStoreIssues(cfg: OpenClawConfig): Promise<string[]> {
546+
if (cfg.gateway?.mode === "remote") {
547+
return [];
548+
}
549+
// Lazy import keeps the migration module a startup-only boundary.
550+
const { listLegacyDevicePairingStoreFiles } =
551+
await import("../infra/device-pairing-migration.js");
552+
return (await listLegacyDevicePairingStoreFiles()).map(formatLegacyPairingStoreIssue);
543553
}
544554

545555
function stripListMarker(message: string): string {
@@ -586,70 +596,61 @@ function localDeviceAuthIssueToHealthFinding(issue: LocalDeviceAuthIssue): Healt
586596
};
587597
}
588598

589-
function pairingStoreReadIssueToHealthFinding(error: JsonFileReadError): HealthFinding {
599+
function legacyPairingStoreIssueToHealthFinding(message: string): HealthFinding {
590600
return {
591601
checkId: DEVICE_PAIRING_CHECK_ID,
592602
severity: "warning",
593-
message: stripListMarker(formatPairingStoreReadIssue(error)),
594-
path: error.filePath,
595-
requirement: `pairing-store-${error.reason}`,
596-
fixHint: "Fix the JSON or file permissions, or move the store aside and re-pair devices.",
603+
message: stripListMarker(message),
604+
path: "devices.legacy-store",
605+
requirement: "pairing-store-legacy-file",
606+
fixHint:
607+
"Restart the gateway so it imports the legacy store; if the file persists, fix or move it aside first.",
597608
};
598609
}
599610

600611
export async function collectDevicePairingHealthFindings(params: {
601612
cfg: OpenClawConfig;
602613
healthOk?: boolean;
603614
}): Promise<HealthFinding[]> {
604-
let snapshot: DoctorPairingSnapshot | null;
605-
try {
606-
snapshot = await loadDoctorPairingSnapshot({
607-
cfg: params.cfg,
608-
healthOk: params.healthOk ?? false,
609-
});
610-
} catch (error) {
611-
if (error instanceof JsonFileReadError) {
612-
return [pairingStoreReadIssueToHealthFinding(error)];
613-
}
614-
throw error;
615-
}
615+
const legacyStoreFindings = (await collectLegacyPairingStoreIssues(params.cfg)).map(
616+
legacyPairingStoreIssueToHealthFinding,
617+
);
618+
const snapshot = await loadDoctorPairingSnapshot({
619+
cfg: params.cfg,
620+
healthOk: params.healthOk ?? false,
621+
});
616622
if (!snapshot) {
617-
return [];
623+
return legacyStoreFindings;
618624
}
619625
return [
626+
...legacyStoreFindings,
620627
...collectPendingPairingIssues(snapshot).map(pendingPairingIssueToHealthFinding),
621628
...collectPairedRecordIssues(snapshot).map(pairedRecordIssueToHealthFinding),
622629
...collectLocalDeviceAuthIssues(snapshot).map(localDeviceAuthIssueToHealthFinding),
623630
];
624631
}
625632

626633
/**
627-
* Emits device pairing repair guidance from live gateway state or local pairing files.
634+
* Emits device pairing repair guidance from live gateway state or the local pairing store.
628635
*
629-
* Remote gateways only report through the gateway API; local gateways can fall back to on-disk
630-
* pairing state when the gateway is down.
636+
* Remote gateways only report through the gateway API; local gateways can fall back to the
637+
* local SQLite pairing state when the gateway is down.
631638
*/
632639
export async function noteDevicePairingHealth(params: {
633640
cfg: OpenClawConfig;
634641
healthOk: boolean;
635642
}): Promise<void> {
636-
let snapshot: DoctorPairingSnapshot | null;
637-
try {
638-
snapshot = await loadDoctorPairingSnapshot(params);
639-
} catch (error) {
640-
if (error instanceof JsonFileReadError) {
641-
note(formatPairingStoreReadIssue(error), "Device pairing");
642-
return;
643-
}
644-
throw error;
645-
}
646-
if (!snapshot) {
647-
return;
648-
}
643+
const legacyStoreLines = await collectLegacyPairingStoreIssues(params.cfg);
644+
const snapshot = await loadDoctorPairingSnapshot(params);
649645
const lines = [
650-
...collectPendingPairingIssues(snapshot).map(formatPendingPairingIssue),
651-
...collectPairedRecordIssues(snapshot).map(formatPairedRecordIssue),
652-
...collectLocalDeviceAuthIssues(snapshot).map(formatLocalDeviceAuthIssue),
646+
...legacyStoreLines,
647+
...(snapshot
648+
? [
649+
...collectPendingPairingIssues(snapshot).map(formatPendingPairingIssue),
650+
...collectPairedRecordIssues(snapshot).map(formatPairedRecordIssue),
651+
...collectLocalDeviceAuthIssues(snapshot).map(formatLocalDeviceAuthIssue),
652+
]
653+
: []),
653654
];
654655
if (lines.length === 0) {
655656
return;

‎src/gateway/probe.auth.integration.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import fs from "node:fs";
44
import path from "node:path";
55
import { afterAll, beforeAll, describe, expect, it } from "vitest";
6+
import { listDevicePairing } from "../infra/device-pairing.js";
67
import { createGatewaySuiteHarness, installGatewayTestHooks, testState } from "./test-helpers.js";
78

89
installGatewayTestHooks({ scope: "suite" });
@@ -109,8 +110,9 @@ describe("probeGateway auth integration", () => {
109110
expect(result.status).toBeNull();
110111
expect(result.configSnapshot).toBeNull();
111112
expect(result.auth.capability).toBe("connected_no_operator_scope");
112-
expect(fs.existsSync(statePath("devices", "paired.json"))).toBe(false);
113-
expect(fs.existsSync(statePath("devices", "pending.json"))).toBe(false);
113+
const pairing = await listDevicePairing();
114+
expect(pairing.paired).toEqual([]);
115+
expect(pairing.pending).toEqual([]);
114116
expect(fs.existsSync(statePath("identity", "device-auth.json"))).toBe(false);
115117
});
116118

0 commit comments

Comments
 (0)