Skip to content

Commit 09a7158

Browse files
qdivanobviyus
andauthored
fix: prevent device pairing migration crash on contaminated records
Closes #134340 ## What Problem This Solves Operators upgrading from the retired JSON device-pairing store can have pending requests or malformed values inside `devices/paired.json`. One bad record aborts the full JSON-to-SQLite import, keeps every valid pairing out of SQLite, and repeats the failed migration on each gateway start. The pairing migration failure is caught and logged. It does not stop gateway startup by itself. The field report also contained a separate legacy session-store blocker. ## Why This Change Was Made The migration now validates every field that SQLite binds directly. It skips records with invalid required pairing data. When only optional metadata is malformed, it omits that field and preserves the usable pairing. The original legacy store is archived only after the safe import completes. Validation includes required timestamps, optional `lastSeenAtMs`, and optional text columns. Separate warnings report skipped records and omitted optional fields. The SQLite mapper remains strict, and no schema or fallback path changes. ## User Impact Valid device pairings survive an upgrade even when the legacy file also contains pending requests or malformed records. The gateway completes the import once and does not retry it after restart. ## Evidence - Current-main red at `77fee957919f06dbaff09dd5cc7f9664d9655651`: a normal isolated gateway logged `NOT NULL constraint failed: device_pairing_paired.created_at_ms` for a pending-shaped leaf and retained `paired.json`. - Anti-cheat red: changing the malformed leaf to `lastSeenAtMs: 1e100` logged `cannot store REAL value in INTEGER column device_pairing_paired.last_seen_at_ms`. - Regression red on contributor head `ee7ea2bfbc5bde3e1b6f90ea58e4d070b7e7ff61`: the expanded boundary test failed with `Provided value cannot be bound to SQLite parameter 47`. - Fixed-head boundary proof: `node scripts/run-vitest.mjs src/infra/device-pairing-migration.test.ts` passed 7/7; targeted formatting and Oxlint passed. - Optional-preservation red on `4f47648f1d6bcf279697d4e8ec5044960bb27cf5`: the corrected regression failed because only one row imported instead of preserving three usable pairings. - Final real gateway proof: startup returned `status=started`, imported three usable pairings, stored malformed optional metadata as `NULL`, skipped one record with invalid required data, archived `paired.json`, and restarted with no migration log. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent c1f527d commit 09a7158

2 files changed

Lines changed: 112 additions & 2 deletions

File tree

‎src/infra/device-pairing-migration.test.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ function legacyPairedDevice(deviceId: string, extra: Partial<PairedDevice> = {})
5555

5656
async function writeLegacyFiles(
5757
baseDir: string,
58-
files: { paired?: Record<string, PairedDevice>; pending?: unknown; bootstrap?: unknown },
58+
files: { paired?: Record<string, unknown>; pending?: unknown; bootstrap?: unknown },
5959
): Promise<string> {
6060
const devicesDir = path.join(baseDir, "devices");
6161
await fs.mkdir(devicesDir, { recursive: true });
@@ -146,6 +146,51 @@ describe("migrateLegacyDevicePairingStore", () => {
146146
expect((await getPairedDevice("device-a", baseDir))?.publicKey).toBe("pk-current");
147147
});
148148

149+
test("imports usable paired rows while omitting invalid optional fields", async () => {
150+
const baseDir = await suiteRootTracker.make("contaminated-paired");
151+
const devicesDir = await writeLegacyFiles(baseDir, {
152+
paired: {
153+
"device-a": legacyPairedDevice("device-a"),
154+
"request-a": {
155+
requestId: "request-a",
156+
deviceId: "device-a",
157+
publicKey: "pk-device-a",
158+
ts: 1_700_000_000_000,
159+
},
160+
"invalid-timestamp": legacyPairedDevice("invalid-timestamp", {
161+
createdAtMs: 1e100,
162+
}),
163+
"invalid-last-seen": legacyPairedDevice("invalid-last-seen", {
164+
lastSeenAtMs: 1e100,
165+
}),
166+
"invalid-text": {
167+
...legacyPairedDevice("invalid-text"),
168+
displayName: { value: "Device" },
169+
},
170+
},
171+
});
172+
const warnings: string[] = [];
173+
174+
const result = await migrateLegacyDevicePairingStore({
175+
baseDir,
176+
log: { info: () => {}, warn: (message) => warnings.push(message) },
177+
});
178+
179+
expect(result).toEqual({ imported: 3, skippedExisting: 0 });
180+
expect((await getPairedDevice("device-a", baseDir))?.publicKey).toBe("pk-device-a");
181+
const normalizedLastSeen = await getPairedDevice("invalid-last-seen", baseDir);
182+
expect(normalizedLastSeen?.publicKey).toBe("pk-invalid-last-seen");
183+
expect(normalizedLastSeen?.lastSeenAtMs).toBeUndefined();
184+
const normalizedText = await getPairedDevice("invalid-text", baseDir);
185+
expect(normalizedText?.publicKey).toBe("pk-invalid-text");
186+
expect(normalizedText?.displayName).toBeUndefined();
187+
expect(warnings).toEqual([
188+
"device pairing store migration skipped 2 invalid paired record(s)",
189+
"device pairing store migration omitted 2 invalid optional field(s)",
190+
]);
191+
expect(await listDeviceFiles(devicesDir)).toEqual(["paired.json.migrated"]);
192+
});
193+
149194
test("returns null when no legacy files exist", async () => {
150195
const baseDir = await suiteRootTracker.make("empty");
151196
expect(await migrateLegacyDevicePairingStore({ baseDir })).toBeNull();

‎src/infra/device-pairing-migration.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
// setup codes are reissued.
99
import fs from "node:fs/promises";
1010
import path from "node:path";
11+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
1112
import { withPairedDeviceRecords, type PairedDevice } from "./device-pairing.js";
1213
import {
1314
coercePairingStateRecord,
@@ -20,6 +21,50 @@ type LegacyDevicePairingMigrationResult = {
2021
skippedExisting: number;
2122
};
2223

24+
const SQLITE_TEXT_FIELDS = [
25+
"displayName",
26+
"operatorLabel",
27+
"platform",
28+
"deviceFamily",
29+
"clientId",
30+
"clientMode",
31+
"browserOrigin",
32+
"role",
33+
"remoteIp",
34+
"approvedVia",
35+
"lastSeenReason",
36+
] as const satisfies readonly (keyof PairedDevice)[];
37+
38+
function normalizeLegacyPairedDevice(
39+
record: PairedDevice,
40+
): { device: PairedDevice; omittedFields: number } | null {
41+
if (!isRecord(record)) {
42+
return null;
43+
}
44+
if (
45+
typeof record.publicKey !== "string" ||
46+
!record.publicKey.trim() ||
47+
!Number.isSafeInteger(record.createdAtMs) ||
48+
!Number.isSafeInteger(record.approvedAtMs)
49+
) {
50+
return null;
51+
}
52+
53+
const device = { ...record };
54+
let omittedFields = 0;
55+
if (device.lastSeenAtMs !== undefined && !Number.isSafeInteger(device.lastSeenAtMs)) {
56+
delete device.lastSeenAtMs;
57+
omittedFields += 1;
58+
}
59+
for (const field of SQLITE_TEXT_FIELDS) {
60+
if (device[field] !== undefined && typeof device[field] !== "string") {
61+
delete device[field];
62+
omittedFields += 1;
63+
}
64+
}
65+
return { device, omittedFields };
66+
}
67+
2368
async function archiveLegacyFile(filePath: string): Promise<void> {
2469
try {
2570
await fs.rename(filePath, `${filePath}.migrated`);
@@ -66,24 +111,44 @@ export async function migrateLegacyDevicePairingStore(params?: {
66111
const legacyPaired = coercePairingStateRecord<PairedDevice>(pairedRaw);
67112
let imported = 0;
68113
let skippedExisting = 0;
114+
let skippedInvalid = 0;
115+
let omittedInvalidFields = 0;
69116
if (Object.keys(legacyPaired).length > 0) {
70117
await withPairedDeviceRecords(params?.baseDir, (pairedByDeviceId) => {
71118
for (const [rawDeviceId, record] of Object.entries(legacyPaired)) {
72119
const deviceId = rawDeviceId.trim();
73120
if (!deviceId) {
121+
skippedInvalid += 1;
74122
continue;
75123
}
76124
if (pairedByDeviceId[deviceId]) {
77125
skippedExisting += 1;
78126
continue;
79127
}
80-
pairedByDeviceId[deviceId] = { ...record, deviceId };
128+
const normalized = normalizeLegacyPairedDevice(record);
129+
if (!normalized) {
130+
skippedInvalid += 1;
131+
continue;
132+
}
133+
omittedInvalidFields += normalized.omittedFields;
134+
pairedByDeviceId[deviceId] = { ...normalized.device, deviceId };
81135
imported += 1;
82136
}
83137
return { value: undefined, persist: imported > 0 };
84138
});
85139
}
86140

141+
if (skippedInvalid > 0) {
142+
params?.log?.warn(
143+
`device pairing store migration skipped ${skippedInvalid} invalid paired record(s)`,
144+
);
145+
}
146+
if (omittedInvalidFields > 0) {
147+
params?.log?.warn(
148+
`device pairing store migration omitted ${omittedInvalidFields} invalid optional field(s)`,
149+
);
150+
}
151+
87152
await Promise.all([
88153
archiveLegacyFile(pairedPath),
89154
archiveLegacyFile(pendingPath),

0 commit comments

Comments
 (0)