Skip to content

Commit e44dde2

Browse files
authored
fix(gateway): revoke device workers when pairing is removed (#123696)
* fix(gateway): revoke device workers on unpair * refactor(backup): split sqlite verification * refactor(backup): narrow sqlite verifier exports * test(gateway): track worker startup temp state * refactor(backup): preserve sqlite architecture boundary * test(gateway): follow worker startup logger binding * fix(gateway): revoke workers during pairing pruning
1 parent f8be386 commit e44dde2

20 files changed

Lines changed: 552 additions & 175 deletions

‎docs/nodes/index.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,11 @@ disconnect; at that boundary its old worker environment is treated as gone and
454454
the session placement reconciles normally. Pairing itself remains, so a later
455455
reconnect can provision a fresh environment. Legacy pairings without exact node
456456
disconnect history are retained fail-safe rather than expired from unrelated
457-
device activity.
457+
device activity. Removing the device pairing, silently pruning a superseded
458+
pairing, or removing only its node role invalidates clients first, then runs
459+
targeted environment and placement reconciliation; explicit removal waits for
460+
the credential fence before returning success, and the periodic sweep retries
461+
failed provider or placement cleanup.
458462

459463
See [Anthropic: Claude sessions across computers](/providers/anthropic#claude-sessions-across-computers)
460464
for the Control UI behavior and storage sources.

‎docs/plan/runners.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,12 @@ stated honestly (revision 1 undersold this):
186186
(unpaired or ceiling
187187
elapsed → normal orphan/reap path). A device-environment reaper keyed on
188188
unpair/dormancy — not on provider teardown proof — cleans rows,
189-
credentials, and staged refs. Unreferenced terminal environment rows retain
189+
credentials, and staged refs. Explicit device removal, node-role removal, and
190+
silent superseded-pairing pruning share one client-invalidation, credential,
191+
environment, and placement reconciliation flow. Explicit RPCs wait for the
192+
credential fence before success returns; periodic reconciliation retries
193+
failed provider or placement cleanup. Unreferenced
194+
terminal environment rows retain
190195
seven days of operator diagnostics, then prune in bounded post-reconcile
191196
batches; any surviving placement keeps its environment provenance.
192197
Device-side GC of per-session workspace dirs and superseded bundles is a
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import path from "node:path";
2+
import { readStringValue } from "@openclaw/normalization-core/string-coerce";
3+
import {
4+
isArchivePathWithin,
5+
normalizeArchivePath,
6+
normalizeArchiveRoot,
7+
} from "../infra/backup-archive-path-policy.js";
8+
import { isRecord } from "../utils.js";
9+
10+
export type BackupManifest = {
11+
schemaVersion: number;
12+
createdAt: string;
13+
archiveRoot: string;
14+
runtimeVersion: string;
15+
platform: string;
16+
nodeVersion: string;
17+
options?: {
18+
includeWorkspace?: boolean;
19+
};
20+
paths?: {
21+
stateDir?: string;
22+
configPath?: string;
23+
oauthDir?: string;
24+
workspaceDirs?: string[];
25+
};
26+
assets: Array<{
27+
kind: string;
28+
sourcePath: string;
29+
archivePath: string;
30+
}>;
31+
skipped?: Array<{
32+
kind?: string;
33+
sourcePath?: string;
34+
reason?: string;
35+
coveredBy?: string;
36+
}>;
37+
};
38+
39+
export function parseBackupManifest(raw: string): BackupManifest {
40+
let parsed: unknown;
41+
try {
42+
parsed = JSON.parse(raw);
43+
} catch (err) {
44+
throw new Error("Backup manifest is not valid JSON.", { cause: err });
45+
}
46+
47+
if (!isRecord(parsed)) {
48+
throw new Error("Backup manifest must be an object.");
49+
}
50+
if (parsed.schemaVersion !== 1) {
51+
throw new Error(`Unsupported backup manifest schemaVersion: ${String(parsed.schemaVersion)}`);
52+
}
53+
if (typeof parsed.archiveRoot !== "string" || !parsed.archiveRoot.trim()) {
54+
throw new Error("Backup manifest is missing archiveRoot.");
55+
}
56+
if (typeof parsed.createdAt !== "string" || !parsed.createdAt.trim()) {
57+
throw new Error("Backup manifest is missing createdAt.");
58+
}
59+
if (!Array.isArray(parsed.assets)) {
60+
throw new Error("Backup manifest is missing assets.");
61+
}
62+
63+
const assets: BackupManifest["assets"] = [];
64+
for (const asset of parsed.assets) {
65+
if (!isRecord(asset)) {
66+
throw new Error("Backup manifest contains a non-object asset.");
67+
}
68+
if (typeof asset.kind !== "string" || !asset.kind.trim()) {
69+
throw new Error("Backup manifest asset is missing kind.");
70+
}
71+
if (typeof asset.sourcePath !== "string" || !asset.sourcePath.trim()) {
72+
throw new Error("Backup manifest asset is missing sourcePath.");
73+
}
74+
if (typeof asset.archivePath !== "string" || !asset.archivePath.trim()) {
75+
throw new Error("Backup manifest asset is missing archivePath.");
76+
}
77+
assets.push({
78+
kind: asset.kind,
79+
sourcePath: asset.sourcePath,
80+
archivePath: asset.archivePath,
81+
});
82+
}
83+
84+
return {
85+
schemaVersion: 1,
86+
archiveRoot: parsed.archiveRoot,
87+
createdAt: parsed.createdAt,
88+
runtimeVersion:
89+
typeof parsed.runtimeVersion === "string" && parsed.runtimeVersion.trim()
90+
? parsed.runtimeVersion
91+
: "unknown",
92+
platform: typeof parsed.platform === "string" ? parsed.platform : "unknown",
93+
nodeVersion: typeof parsed.nodeVersion === "string" ? parsed.nodeVersion : "unknown",
94+
options: isRecord(parsed.options)
95+
? { includeWorkspace: parsed.options.includeWorkspace as boolean | undefined }
96+
: undefined,
97+
paths: isRecord(parsed.paths)
98+
? {
99+
stateDir: readStringValue(parsed.paths.stateDir),
100+
configPath: readStringValue(parsed.paths.configPath),
101+
oauthDir: readStringValue(parsed.paths.oauthDir),
102+
workspaceDirs: Array.isArray(parsed.paths.workspaceDirs)
103+
? parsed.paths.workspaceDirs.filter(
104+
(entry): entry is string => typeof entry === "string",
105+
)
106+
: undefined,
107+
}
108+
: undefined,
109+
assets,
110+
skipped: Array.isArray(parsed.skipped) ? parsed.skipped : undefined,
111+
};
112+
}
113+
114+
export function isRootBackupManifestEntry(entryPath: string): boolean {
115+
const parts = entryPath.split("/");
116+
return parts.length === 2 && parts[0] !== "" && parts[1] === "manifest.json";
117+
}
118+
119+
export function verifyBackupManifestEntries(manifest: BackupManifest, entries: Set<string>): void {
120+
const archiveRoot = normalizeArchiveRoot(manifest.archiveRoot);
121+
const manifestEntryPath = path.posix.join(archiveRoot, "manifest.json");
122+
const normalizedEntries = [...entries];
123+
const normalizedEntrySet = new Set(normalizedEntries);
124+
125+
if (!normalizedEntrySet.has(manifestEntryPath)) {
126+
throw new Error(`Archive is missing manifest entry: ${manifestEntryPath}`);
127+
}
128+
129+
for (const entry of normalizedEntries) {
130+
if (!isArchivePathWithin(entry, archiveRoot)) {
131+
throw new Error(`Archive entry is outside the declared archive root: ${entry}`);
132+
}
133+
}
134+
135+
const payloadRoot = path.posix.join(archiveRoot, "payload");
136+
for (const asset of manifest.assets) {
137+
const assetArchivePath = normalizeArchivePath(asset.archivePath, "Backup manifest asset path");
138+
if (!isArchivePathWithin(assetArchivePath, payloadRoot)) {
139+
throw new Error(`Manifest asset path is outside payload root: ${asset.archivePath}`);
140+
}
141+
const exact = normalizedEntrySet.has(assetArchivePath);
142+
const nested = normalizedEntries.some(
143+
(entry) => entry !== assetArchivePath && isArchivePathWithin(entry, assetArchivePath),
144+
);
145+
if (!exact && !nested) {
146+
throw new Error(`Archive is missing payload for manifest asset: ${assetArchivePath}`);
147+
}
148+
}
149+
}

‎src/commands/backup-verify.ts‎

Lines changed: 10 additions & 148 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import os from "node:os";
44
import path from "node:path";
55
import type { DatabaseSync } from "node:sqlite";
66
import { toStringifiedError } from "@openclaw/normalization-core/error-coercion";
7-
import { readStringValue } from "@openclaw/normalization-core/string-coerce";
87
import * as tar from "tar";
98
import { loadSqliteVecExtension } from "../../packages/memory-host-sdk/src/engine-storage.js";
109
import {
@@ -18,45 +17,20 @@ import { formatDiskSpaceBytes, tryReadDiskSpace } from "../infra/disk-space.js";
1817
import { openNodeSqliteDatabase } from "../infra/node-sqlite.js";
1918
import { assertSqliteIntegrity } from "../infra/sqlite-integrity.js";
2019
import { type RuntimeEnv, writeRuntimeJson } from "../runtime.js";
21-
import { isRecord, resolveUserPath } from "../utils.js";
20+
import { resolveUserPath } from "../utils.js";
2221
import { BACKUP_MAX_DECOMPRESSION_RATIO, buildBackupArchivePath } from "./backup-shared.js";
22+
import {
23+
type BackupManifest,
24+
isRootBackupManifestEntry,
25+
parseBackupManifest,
26+
verifyBackupManifestEntries,
27+
} from "./backup-verify-manifest.js";
2328

2429
const MAX_MANIFEST_BYTES = 1024 * 1024;
2530
const MAX_SQLITE_SNAPSHOT_EXTRACT_BYTES = 64 * 1024 * 1024 * 1024;
2631
const SQLITE_SNAPSHOT_FREE_SPACE_RESERVE_BYTES = 256 * 1024 * 1024;
2732
const SQLITE_SNAPSHOT_SIDECAR_SUFFIXES = ["-wal", "-shm", "-journal"] as const;
2833

29-
type BackupManifestAsset = {
30-
kind: string;
31-
sourcePath: string;
32-
archivePath: string;
33-
};
34-
35-
type BackupManifest = {
36-
schemaVersion: number;
37-
createdAt: string;
38-
archiveRoot: string;
39-
runtimeVersion: string;
40-
platform: string;
41-
nodeVersion: string;
42-
options?: {
43-
includeWorkspace?: boolean;
44-
};
45-
paths?: {
46-
stateDir?: string;
47-
configPath?: string;
48-
oauthDir?: string;
49-
workspaceDirs?: string[];
50-
};
51-
assets: BackupManifestAsset[];
52-
skipped?: Array<{
53-
kind?: string;
54-
sourcePath?: string;
55-
reason?: string;
56-
coveredBy?: string;
57-
}>;
58-
};
59-
6034
type BackupVerifyOptions = {
6135
archive: string;
6236
json?: boolean;
@@ -93,81 +67,6 @@ type SqliteSnapshotEntry = NormalizedArchiveEntry & {
9367

9468
type ExpectedSqliteRole = "agent" | "global";
9569

96-
function parseManifest(raw: string): BackupManifest {
97-
let parsed: unknown;
98-
try {
99-
parsed = JSON.parse(raw);
100-
} catch (err) {
101-
throw new Error("Backup manifest is not valid JSON.", { cause: err });
102-
}
103-
104-
if (!isRecord(parsed)) {
105-
throw new Error("Backup manifest must be an object.");
106-
}
107-
if (parsed.schemaVersion !== 1) {
108-
throw new Error(`Unsupported backup manifest schemaVersion: ${String(parsed.schemaVersion)}`);
109-
}
110-
if (typeof parsed.archiveRoot !== "string" || !parsed.archiveRoot.trim()) {
111-
throw new Error("Backup manifest is missing archiveRoot.");
112-
}
113-
if (typeof parsed.createdAt !== "string" || !parsed.createdAt.trim()) {
114-
throw new Error("Backup manifest is missing createdAt.");
115-
}
116-
if (!Array.isArray(parsed.assets)) {
117-
throw new Error("Backup manifest is missing assets.");
118-
}
119-
120-
const assets: BackupManifestAsset[] = [];
121-
for (const asset of parsed.assets) {
122-
if (!isRecord(asset)) {
123-
throw new Error("Backup manifest contains a non-object asset.");
124-
}
125-
if (typeof asset.kind !== "string" || !asset.kind.trim()) {
126-
throw new Error("Backup manifest asset is missing kind.");
127-
}
128-
if (typeof asset.sourcePath !== "string" || !asset.sourcePath.trim()) {
129-
throw new Error("Backup manifest asset is missing sourcePath.");
130-
}
131-
if (typeof asset.archivePath !== "string" || !asset.archivePath.trim()) {
132-
throw new Error("Backup manifest asset is missing archivePath.");
133-
}
134-
assets.push({
135-
kind: asset.kind,
136-
sourcePath: asset.sourcePath,
137-
archivePath: asset.archivePath,
138-
});
139-
}
140-
141-
return {
142-
schemaVersion: 1,
143-
archiveRoot: parsed.archiveRoot,
144-
createdAt: parsed.createdAt,
145-
runtimeVersion:
146-
typeof parsed.runtimeVersion === "string" && parsed.runtimeVersion.trim()
147-
? parsed.runtimeVersion
148-
: "unknown",
149-
platform: typeof parsed.platform === "string" ? parsed.platform : "unknown",
150-
nodeVersion: typeof parsed.nodeVersion === "string" ? parsed.nodeVersion : "unknown",
151-
options: isRecord(parsed.options)
152-
? { includeWorkspace: parsed.options.includeWorkspace as boolean | undefined }
153-
: undefined,
154-
paths: isRecord(parsed.paths)
155-
? {
156-
stateDir: readStringValue(parsed.paths.stateDir),
157-
configPath: readStringValue(parsed.paths.configPath),
158-
oauthDir: readStringValue(parsed.paths.oauthDir),
159-
workspaceDirs: Array.isArray(parsed.paths.workspaceDirs)
160-
? parsed.paths.workspaceDirs.filter(
161-
(entry): entry is string => typeof entry === "string",
162-
)
163-
: undefined,
164-
}
165-
: undefined,
166-
assets,
167-
skipped: Array.isArray(parsed.skipped) ? parsed.skipped : undefined,
168-
};
169-
}
170-
17170
async function listArchiveEntries(archivePath: string): Promise<ArchiveEntry[]> {
17271
const entries: ArchiveEntry[] = [];
17372
await tar.t({
@@ -215,43 +114,6 @@ async function extractManifest(params: {
215114
return content.toString("utf8");
216115
}
217116

218-
function isRootManifestEntry(entryPath: string): boolean {
219-
const parts = entryPath.split("/");
220-
return parts.length === 2 && parts[0] !== "" && parts[1] === "manifest.json";
221-
}
222-
223-
function verifyManifestAgainstEntries(manifest: BackupManifest, entries: Set<string>): void {
224-
const archiveRoot = normalizeArchiveRoot(manifest.archiveRoot);
225-
const manifestEntryPath = path.posix.join(archiveRoot, "manifest.json");
226-
const normalizedEntries = [...entries];
227-
const normalizedEntrySet = new Set(normalizedEntries);
228-
229-
if (!normalizedEntrySet.has(manifestEntryPath)) {
230-
throw new Error(`Archive is missing manifest entry: ${manifestEntryPath}`);
231-
}
232-
233-
for (const entry of normalizedEntries) {
234-
if (!isArchivePathWithin(entry, archiveRoot)) {
235-
throw new Error(`Archive entry is outside the declared archive root: ${entry}`);
236-
}
237-
}
238-
239-
const payloadRoot = path.posix.join(archiveRoot, "payload");
240-
for (const asset of manifest.assets) {
241-
const assetArchivePath = normalizeArchivePath(asset.archivePath, "Backup manifest asset path");
242-
if (!isArchivePathWithin(assetArchivePath, payloadRoot)) {
243-
throw new Error(`Manifest asset path is outside payload root: ${asset.archivePath}`);
244-
}
245-
const exact = normalizedEntrySet.has(assetArchivePath);
246-
const nested = normalizedEntries.some(
247-
(entry) => entry !== assetArchivePath && isArchivePathWithin(entry, assetArchivePath),
248-
);
249-
if (!exact && !nested) {
250-
throw new Error(`Archive is missing payload for manifest asset: ${assetArchivePath}`);
251-
}
252-
}
253-
}
254-
255117
function verifyHardlinkTargetsAgainstArchiveRoot(
256118
hardlinkTargets: Array<{ entryPath: string; normalized: string }>,
257119
archiveRoot: string,
@@ -705,7 +567,7 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
705567
.map((entry) => ({ entryPath: entry.path, linkpath: entry.linkpath }));
706568
const normalizedEntrySet = new Set(entries.map((entry) => entry.normalized));
707569

708-
const manifestMatches = entries.filter((entry) => isRootManifestEntry(entry.normalized));
570+
const manifestMatches = entries.filter((entry) => isRootBackupManifestEntry(entry.normalized));
709571
if (manifestMatches.length !== 1) {
710572
throw new Error(`Expected exactly one backup manifest entry, found ${manifestMatches.length}.`);
711573
}
@@ -725,8 +587,8 @@ export async function verifyBackupArchive(archive: string): Promise<BackupVerify
725587
}
726588

727589
const manifestRaw = await extractManifest({ archivePath, manifestEntryPath });
728-
const manifest = parseManifest(manifestRaw);
729-
verifyManifestAgainstEntries(manifest, normalizedEntrySet);
590+
const manifest = parseBackupManifest(manifestRaw);
591+
verifyBackupManifestEntries(manifest, normalizedEntrySet);
730592
verifyHardlinkTargetsAgainstArchiveRoot(
731593
hardlinkTargets,
732594
manifest.archiveRoot,

0 commit comments

Comments
 (0)