Skip to content

Commit 20bd49d

Browse files
fix(pairing): normalize account key in legacy allowFrom filename parsing (#110415)
* [AI] fix(pairing): normalize account key in legacy allowFrom filename parsing parseAllowFromFilename extracted the account segment from filenames without normalizing it via safeAccountKey, so non-canonical spellings (e.g. HY_RIN_Bot vs hy_rin_bot) could never match configured accounts. This left the file unresolved, producing a startup migration warning that blocks gateway readiness on every restart. Normalize accountKey via safeAccountKey before comparing so that raw and canonical spellings resolve to the same account. Wrap in try/catch so pathological filename segments skip safely instead of throwing. Guard non-canonical DEFAULT segments: when safeAccountKey maps a non-literal-default segment (e.g. "DEFAULT") to the canonical key "default", skip the filter so the file remains unresolved instead of being attributed to the implicit bundled default account and deleted. Keep the implicit bundled-default fallback on the literal canonical suffix (accountKey === DEFAULT_ACCOUNT_ID). Ambiguity detection remains unchanged. Related to #110187 * fix(pairing): constrain legacy filename recovery Co-authored-by: WangYan <[email protected]> * fix(pairing): preserve case-colliding legacy files Co-authored-by: WangYan <[email protected]> * fix(pairing): match legacy files to raw account ids Co-authored-by: WangYan <[email protected]> * fix(pairing): keep default suffix literal Co-authored-by: WangYan <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent a124966 commit 20bd49d

3 files changed

Lines changed: 172 additions & 12 deletions

File tree

‎src/commands/doctor-state-migrations.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1437,6 +1437,32 @@ describe("doctor legacy state migrations", () => {
14371437
expect(fs.existsSync(path.join(oauthDir, "telegram-allowFrom.json"))).toBe(false);
14381438
});
14391439

1440+
it("migrates a case-preserved Telegram account filename through Doctor", async () => {
1441+
const root = await makeTempRoot();
1442+
const cfg: OpenClawConfig = {
1443+
channels: {
1444+
telegram: {
1445+
accounts: {
1446+
HY_RIN_Bot: {},
1447+
},
1448+
},
1449+
},
1450+
};
1451+
const oauthDir = ensureCredentialsDir(root);
1452+
const sourcePath = path.join(oauthDir, "telegram-HY_RIN_Bot-allowFrom.json");
1453+
fs.writeFileSync(sourcePath, '["1008"]\n', "utf8");
1454+
const env = { OPENCLAW_STATE_DIR: root } as NodeJS.ProcessEnv;
1455+
1456+
const detected = await detectLegacyStateMigrations({ cfg, env });
1457+
const result = await runLegacyStateMigrations({ detected, config: cfg, env, now: () => 123 });
1458+
1459+
expect(result.warnings).toStrictEqual([]);
1460+
expect(readChannelPairingStateSnapshot("telegram", env).allowFrom).toEqual({
1461+
hy_rin_bot: ["1008"],
1462+
});
1463+
expect(fs.existsSync(sourcePath)).toBe(false);
1464+
});
1465+
14401466
it("no-ops when nothing detected", async () => {
14411467
const root = await makeTempRoot();
14421468
const cfg: OpenClawConfig = {};

‎src/infra/state-migrations.channel-pairing.test.ts‎

Lines changed: 103 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ function writeJson(filePath: string, value: unknown): void {
3232
fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
3333
}
3434

35+
function isCaseSensitiveDirectory(directory: string): boolean {
36+
const marker = path.join(directory, "case-check");
37+
fs.writeFileSync(marker, "case", "utf8");
38+
const caseSensitive = !fs.existsSync(path.join(directory, "CASE-CHECK"));
39+
fs.rmSync(marker);
40+
return caseSensitive;
41+
}
42+
3543
describe("legacy channel pairing state migration", () => {
3644
it("imports pairing requests and scoped allowFrom entries into SQLite", async () => {
3745
const { env, sourceDir } = await createFixture();
@@ -57,7 +65,7 @@ describe("legacy channel pairing state migration", () => {
5765

5866
const detected = detectLegacyChannelPairingState({
5967
sourceDir,
60-
configuredAccountIds: { telegram: ["alerts", "ops/bot"] },
68+
configuredAccountIds: { telegram: ["alerts", "ops_bot"] },
6169
});
6270
expect(detected.hasLegacy).toBe(true);
6371
const result = migrateLegacyChannelPairingState({ detected, env });
@@ -76,7 +84,7 @@ describe("legacy channel pairing state migration", () => {
7684
meta: { accountId: "alerts" },
7785
},
7886
],
79-
allowFrom: { default: ["1001"], alerts: ["1002"], "ops/bot": ["1003"] },
87+
allowFrom: { default: ["1001"], alerts: ["1002"], ops_bot: ["1003"] },
8088
});
8189
expect(fs.existsSync(path.join(path.dirname(sourceDir), "state", "openclaw.sqlite"))).toBe(
8290
true,
@@ -159,9 +167,9 @@ describe("legacy channel pairing state migration", () => {
159167
});
160168
});
161169

162-
it("leaves ambiguous sanitized account filenames in place", async () => {
170+
it("matches the raw account key instead of a punctuation-normalized sibling", async () => {
163171
const { env, sourceDir } = await createFixture();
164-
const filePath = path.join(sourceDir, "telegram-ops_bot-allowFrom.json");
172+
const filePath = path.join(sourceDir, "telegram-Ops_Bot-allowFrom.json");
165173
writeJson(filePath, { version: 1, allowFrom: ["1003"] });
166174

167175
const detected = detectLegacyChannelPairingState({
@@ -170,16 +178,81 @@ describe("legacy channel pairing state migration", () => {
170178
});
171179
const result = migrateLegacyChannelPairingState({ detected, env });
172180

181+
expect(result.warnings).toEqual([]);
182+
expect(result.changes).toEqual([
183+
"Migrated 1 telegram/ops_bot allowFrom entry → shared SQLite state",
184+
]);
185+
expect(fs.existsSync(filePath)).toBe(false);
186+
expect(readChannelPairingStateSnapshot("telegram", env).allowFrom).toEqual({
187+
ops_bot: ["1003"],
188+
});
189+
});
190+
191+
it("leaves case-folded filename collision sets in place", async () => {
192+
const { env, sourceDir } = await createFixture();
193+
const caseSensitive = isCaseSensitiveDirectory(sourceDir);
194+
if (!caseSensitive) {
195+
expect(caseSensitive).toBe(false);
196+
return;
197+
}
198+
const filenames = [
199+
"telegram-AmbiguousAcct-allowFrom.json",
200+
"telegram-AMBIGUOUSACCT-allowFrom.json",
201+
"telegram-exactacct-allowFrom.json",
202+
"telegram-ExactAcct-allowFrom.json",
203+
];
204+
for (const [index, filename] of filenames.entries()) {
205+
writeJson(path.join(sourceDir, filename), { version: 1, allowFrom: [`user-${index}`] });
206+
}
207+
208+
const detected = detectLegacyChannelPairingState({
209+
sourceDir,
210+
configuredAccountIds: { telegram: ["ambiguousacct", "exactacct"] },
211+
});
212+
const result = migrateLegacyChannelPairingState({ detected, env });
213+
173214
expect(result.changes).toEqual([]);
174-
expect(result.warnings).toEqual([
175-
expect.stringContaining(
176-
"Legacy channel allowFrom channel/account is ambiguous; left in place",
215+
expect(result.warnings).toHaveLength(filenames.length);
216+
expect(result.warnings).toEqual(
217+
expect.arrayContaining(
218+
filenames.map((filename) =>
219+
expect.stringContaining(
220+
`Legacy channel allowFrom channel/account is ambiguous; left in place at ${path.join(sourceDir, filename)}`,
221+
),
222+
),
177223
),
178-
]);
179-
expect(fs.existsSync(filePath)).toBe(true);
224+
);
225+
expect(filenames.every((filename) => fs.existsSync(path.join(sourceDir, filename)))).toBe(true);
180226
expect(readChannelPairingStateSnapshot("telegram", env).allowFrom).toEqual({});
181227
});
182228

229+
it.each([
230+
{ filenameAccountKey: "ops..bot", configuredAccountId: "ops_bot" },
231+
{ filenameAccountKey: "ops_bot", configuredAccountId: "ops.bot" },
232+
])(
233+
"does not re-encode $filenameAccountKey into $configuredAccountId",
234+
async ({ filenameAccountKey, configuredAccountId }) => {
235+
const { env, sourceDir } = await createFixture();
236+
const filePath = path.join(sourceDir, `telegram-${filenameAccountKey}-allowFrom.json`);
237+
writeJson(filePath, { version: 1, allowFrom: ["1003"] });
238+
239+
const detected = detectLegacyChannelPairingState({
240+
sourceDir,
241+
configuredAccountIds: { telegram: [configuredAccountId] },
242+
});
243+
const result = migrateLegacyChannelPairingState({ detected, env });
244+
245+
expect(result.changes).toEqual([]);
246+
expect(result.warnings).toEqual([
247+
expect.stringContaining(
248+
"Legacy channel allowFrom channel/account is unresolved; left in place",
249+
),
250+
]);
251+
expect(fs.existsSync(filePath)).toBe(true);
252+
expect(readChannelPairingStateSnapshot("telegram", env).allowFrom).toEqual({});
253+
},
254+
);
255+
183256
it("ignores invalid account candidates while resolving scoped filenames", async () => {
184257
const { env, sourceDir } = await createFixture();
185258
const filePath = path.join(sourceDir, "telegram-alerts-allowFrom.json");
@@ -201,6 +274,27 @@ describe("legacy channel pairing state migration", () => {
201274
});
202275
});
203276

277+
it("leaves nonliteral default filename suffixes unresolved", async () => {
278+
const { env, sourceDir } = await createFixture();
279+
const filePath = path.join(sourceDir, "telegram-DEFAULT-allowFrom.json");
280+
writeJson(filePath, { version: 1, allowFrom: ["1003"] });
281+
282+
const detected = detectLegacyChannelPairingState({
283+
sourceDir,
284+
configuredAccountIds: { telegram: ["default"] },
285+
});
286+
const result = migrateLegacyChannelPairingState({ detected, env });
287+
288+
expect(result.changes).toEqual([]);
289+
expect(result.warnings).toEqual([
290+
expect.stringContaining(
291+
"Legacy channel allowFrom channel/account is unresolved; left in place",
292+
),
293+
]);
294+
expect(fs.existsSync(filePath)).toBe(true);
295+
expect(readChannelPairingStateSnapshot("telegram", env).allowFrom).toEqual({});
296+
});
297+
204298
it("does not infer default accounts for external channels", async () => {
205299
const { env, sourceDir } = await createFixture();
206300
const filePath = path.join(sourceDir, "custom-channel-default-allowFrom.json");

‎src/infra/state-migrations.channel-pairing.ts‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,35 @@ function parsePairingFilename(filename: string): PairingChannel | null {
7878
: null;
7979
}
8080

81+
function findCaseFoldedAllowFromCollisions(
82+
filenames: readonly string[],
83+
knownChannelIds: readonly string[],
84+
): Set<string> {
85+
const firstFilenameByKey = new Map<string, string>();
86+
const collisions = new Set<string>();
87+
for (const filename of filenames) {
88+
if (!filename.endsWith(ALLOW_FROM_SUFFIX)) {
89+
continue;
90+
}
91+
const stem = filename.slice(0, -ALLOW_FROM_SUFFIX.length);
92+
for (const channel of knownChannelIds) {
93+
if (!stem.startsWith(`${channel}-`)) {
94+
continue;
95+
}
96+
const accountKey = stem.slice(channel.length + 1).toLowerCase();
97+
const collisionKey = `${channel}\0${accountKey}`;
98+
const firstFilename = firstFilenameByKey.get(collisionKey);
99+
if (firstFilename) {
100+
collisions.add(firstFilename);
101+
collisions.add(filename);
102+
} else {
103+
firstFilenameByKey.set(collisionKey, filename);
104+
}
105+
}
106+
}
107+
return collisions;
108+
}
109+
81110
function parseAllowFromFilename(
82111
filename: string,
83112
knownChannelIds: readonly string[],
@@ -105,9 +134,14 @@ function parseAllowFromFilename(
105134
continue;
106135
}
107136
const accountKey = stem.slice(channel.length + 1);
137+
// Fold case only: either side may contain punctuation that safe-key encoding would conflate.
108138
const matchingAccountIds = (accountIds[channel] ?? []).filter((accountId) => {
109139
try {
110-
return safeAccountKey(accountId) === accountKey;
140+
safeAccountKey(accountId);
141+
if (accountId === DEFAULT_ACCOUNT_ID && accountKey !== DEFAULT_ACCOUNT_ID) {
142+
return false;
143+
}
144+
return accountId.toLowerCase() === accountKey.toLowerCase();
111145
} catch {
112146
// One invalid configured candidate must not abort every legacy migration.
113147
// With no valid match, the source remains in place as unresolved below.
@@ -241,6 +275,10 @@ export function migrateLegacyChannelPairingState(params: {
241275
}): { changes: string[]; warnings: string[] } {
242276
const changes: string[] = [];
243277
const warnings: string[] = [];
278+
const caseFoldedCollisions = findCaseFoldedAllowFromCollisions(
279+
params.detected.files,
280+
params.detected.knownChannelIds,
281+
);
244282
for (const filename of params.detected.files) {
245283
const filePath = path.join(params.detected.sourceDir, filename);
246284
const pairingChannel = parsePairingFilename(filename);
@@ -269,8 +307,10 @@ export function migrateLegacyChannelPairingState(params: {
269307
if (!allowTarget) {
270308
continue;
271309
}
272-
if (!allowTarget.target) {
273-
const reason = allowTarget.reason === "ambiguous" ? "ambiguous" : "unresolved";
310+
const hasCaseFoldedCollision = caseFoldedCollisions.has(filename);
311+
if (hasCaseFoldedCollision || !allowTarget.target) {
312+
const reason =
313+
hasCaseFoldedCollision || allowTarget.reason === "ambiguous" ? "ambiguous" : "unresolved";
274314
warnings.push(
275315
`Legacy channel allowFrom channel/account is ${reason}; left in place at ${filePath}`,
276316
);

0 commit comments

Comments
 (0)