Skip to content

Commit f4f0b17

Browse files
committed
Matrix: isolate credential write runtime
1 parent 8c01347 commit f4f0b17

7 files changed

Lines changed: 207 additions & 171 deletions

File tree

‎extensions/matrix/src/matrix/accounts.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
resolveMatrixAccount,
88
} from "./accounts.js";
99

10-
vi.mock("./credentials.js", () => ({
10+
vi.mock("./credentials-read.js", () => ({
1111
loadMatrixCredentials: () => null,
1212
credentialsMatchConfig: () => false,
1313
}));

‎extensions/matrix/src/matrix/accounts.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
import type { CoreConfig, MatrixConfig } from "../types.js";
1111
import { findMatrixAccountConfig, resolveMatrixBaseConfig } from "./account-config.js";
1212
import { resolveMatrixConfigForAccount } from "./client.js";
13-
import { credentialsMatchConfig, loadMatrixCredentials } from "./credentials.js";
13+
import { credentialsMatchConfig, loadMatrixCredentials } from "./credentials-read.js";
1414

1515
/** Merge account config with top-level defaults, preserving nested objects. */
1616
function mergeAccountConfig(base: MatrixConfig, account: MatrixConfig): MatrixConfig {

‎extensions/matrix/src/matrix/client.test.ts‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,20 @@ import {
99
resolveMatrixAuthContext,
1010
validateMatrixHomeserverUrl,
1111
} from "./client/config.js";
12-
import * as credentialsModule from "./credentials.js";
12+
import * as credentialsReadModule from "./credentials-read.js";
1313
import * as sdkModule from "./sdk.js";
1414

1515
const saveMatrixCredentialsMock = vi.hoisted(() => vi.fn());
16+
const touchMatrixCredentialsMock = vi.hoisted(() => vi.fn());
1617

17-
vi.mock("./credentials.js", () => ({
18+
vi.mock("./credentials-read.js", () => ({
1819
loadMatrixCredentials: vi.fn(() => null),
19-
saveMatrixCredentials: saveMatrixCredentialsMock,
2020
credentialsMatchConfig: vi.fn(() => false),
21-
touchMatrixCredentials: vi.fn(),
21+
}));
22+
23+
vi.mock("./credentials-write.runtime.js", () => ({
24+
saveMatrixCredentials: saveMatrixCredentialsMock,
25+
touchMatrixCredentials: touchMatrixCredentialsMock,
2226
}));
2327

2428
describe("resolveMatrixConfig", () => {
@@ -414,14 +418,14 @@ describe("resolveMatrixAuth", () => {
414418
});
415419

416420
it("uses cached matching credentials when access token is not configured", async () => {
417-
vi.mocked(credentialsModule.loadMatrixCredentials).mockReturnValue({
421+
vi.mocked(credentialsReadModule.loadMatrixCredentials).mockReturnValue({
418422
homeserver: "https://matrix.example.org",
419423
userId: "@bot:example.org",
420424
accessToken: "cached-token",
421425
deviceId: "CACHEDDEVICE",
422426
createdAt: "2026-01-01T00:00:00.000Z",
423427
});
424-
vi.mocked(credentialsModule.credentialsMatchConfig).mockReturnValue(true);
428+
vi.mocked(credentialsReadModule.credentialsMatchConfig).mockReturnValue(true);
425429

426430
const cfg = {
427431
channels: {
@@ -464,13 +468,13 @@ describe("resolveMatrixAuth", () => {
464468
});
465469

466470
it("falls back to config deviceId when cached credentials are missing it", async () => {
467-
vi.mocked(credentialsModule.loadMatrixCredentials).mockReturnValue({
471+
vi.mocked(credentialsReadModule.loadMatrixCredentials).mockReturnValue({
468472
homeserver: "https://matrix.example.org",
469473
userId: "@bot:example.org",
470474
accessToken: "tok-123",
471475
createdAt: "2026-01-01T00:00:00.000Z",
472476
});
473-
vi.mocked(credentialsModule.credentialsMatchConfig).mockReturnValue(true);
477+
vi.mocked(credentialsReadModule.credentialsMatchConfig).mockReturnValue(true);
474478

475479
const cfg = {
476480
channels: {
@@ -533,8 +537,8 @@ describe("resolveMatrixAuth", () => {
533537
});
534538

535539
it("uses named-account password auth instead of inheriting the base access token", async () => {
536-
vi.mocked(credentialsModule.loadMatrixCredentials).mockReturnValue(null);
537-
vi.mocked(credentialsModule.credentialsMatchConfig).mockReturnValue(false);
540+
vi.mocked(credentialsReadModule.loadMatrixCredentials).mockReturnValue(null);
541+
vi.mocked(credentialsReadModule.credentialsMatchConfig).mockReturnValue(false);
538542
const doRequestSpy = vi.spyOn(sdkModule.MatrixClient.prototype, "doRequest").mockResolvedValue({
539543
access_token: "ops-token",
540544
user_id: "@ops:example.org",
@@ -615,13 +619,13 @@ describe("resolveMatrixAuth", () => {
615619
});
616620

617621
it("uses config deviceId with cached credentials when token is loaded from cache", async () => {
618-
vi.mocked(credentialsModule.loadMatrixCredentials).mockReturnValue({
622+
vi.mocked(credentialsReadModule.loadMatrixCredentials).mockReturnValue({
619623
homeserver: "https://matrix.example.org",
620624
userId: "@bot:example.org",
621625
accessToken: "tok-123",
622626
createdAt: "2026-01-01T00:00:00.000Z",
623627
});
624-
vi.mocked(credentialsModule.credentialsMatchConfig).mockReturnValue(true);
628+
vi.mocked(credentialsReadModule.credentialsMatchConfig).mockReturnValue(true);
625629

626630
const cfg = {
627631
channels: {

‎extensions/matrix/src/matrix/client/config.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
listNormalizedMatrixAccountIds,
2020
} from "../account-config.js";
2121
import { resolveMatrixConfigFieldPath } from "../config-update.js";
22+
import { credentialsMatchConfig, loadMatrixCredentials } from "../credentials-read.js";
2223
import { MatrixClient } from "../sdk.js";
2324
import { ensureMatrixSdkLoggingConfigured } from "./logging.js";
2425
import type { MatrixAuth, MatrixResolvedConfig } from "./types.js";
@@ -338,13 +339,11 @@ export async function resolveMatrixAuth(params?: {
338339
}): Promise<MatrixAuth> {
339340
const { cfg, env, accountId, resolved } = resolveMatrixAuthContext(params);
340341
const homeserver = validateMatrixHomeserverUrl(resolved.homeserver);
341-
342-
const {
343-
loadMatrixCredentials,
344-
saveMatrixCredentials,
345-
credentialsMatchConfig,
346-
touchMatrixCredentials,
347-
} = await import("../credentials.js");
342+
let credentialsWriter: typeof import("../credentials-write.runtime.js") | undefined;
343+
const loadCredentialsWriter = async () => {
344+
credentialsWriter ??= await import("../credentials-write.runtime.js");
345+
return credentialsWriter;
346+
};
348347

349348
const cached = loadMatrixCredentials(env, accountId);
350349
const cachedCredentials =
@@ -391,6 +390,7 @@ export async function resolveMatrixAuth(params?: {
391390
cachedCredentials.userId !== userId ||
392391
(cachedCredentials.deviceId || undefined) !== knownDeviceId;
393392
if (shouldRefreshCachedCredentials) {
393+
const { saveMatrixCredentials } = await loadCredentialsWriter();
394394
await saveMatrixCredentials(
395395
{
396396
homeserver,
@@ -402,6 +402,7 @@ export async function resolveMatrixAuth(params?: {
402402
accountId,
403403
);
404404
} else if (hasMatchingCachedToken) {
405+
const { touchMatrixCredentials } = await loadCredentialsWriter();
405406
await touchMatrixCredentials(env, accountId);
406407
}
407408
return {
@@ -418,6 +419,7 @@ export async function resolveMatrixAuth(params?: {
418419
}
419420

420421
if (cachedCredentials) {
422+
const { touchMatrixCredentials } = await loadCredentialsWriter();
421423
await touchMatrixCredentials(env, accountId);
422424
return {
423425
accountId,
@@ -474,6 +476,7 @@ export async function resolveMatrixAuth(params?: {
474476
encryption: resolved.encryption,
475477
};
476478

479+
const { saveMatrixCredentials } = await loadCredentialsWriter();
477480
await saveMatrixCredentials(
478481
{
479482
homeserver: auth.homeserver,
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "openclaw/plugin-sdk/account-id";
5+
import {
6+
requiresExplicitMatrixDefaultAccount,
7+
resolveMatrixDefaultOrOnlyAccountId,
8+
} from "../account-selection.js";
9+
import { getMatrixRuntime } from "../runtime.js";
10+
import {
11+
resolveMatrixCredentialsDir as resolveSharedMatrixCredentialsDir,
12+
resolveMatrixCredentialsPath as resolveSharedMatrixCredentialsPath,
13+
} from "../storage-paths.js";
14+
15+
export type MatrixStoredCredentials = {
16+
homeserver: string;
17+
userId: string;
18+
accessToken: string;
19+
deviceId?: string;
20+
createdAt: string;
21+
lastUsedAt?: string;
22+
};
23+
24+
function resolveStateDir(env: NodeJS.ProcessEnv): string {
25+
return getMatrixRuntime().state.resolveStateDir(env, os.homedir);
26+
}
27+
28+
function resolveLegacyMatrixCredentialsPath(env: NodeJS.ProcessEnv): string | null {
29+
return path.join(resolveMatrixCredentialsDir(env), "credentials.json");
30+
}
31+
32+
function shouldReadLegacyCredentialsForAccount(accountId?: string | null): boolean {
33+
const normalizedAccountId = normalizeAccountId(accountId);
34+
const cfg = getMatrixRuntime().config.loadConfig();
35+
if (!cfg.channels?.matrix || typeof cfg.channels.matrix !== "object") {
36+
return normalizedAccountId === DEFAULT_ACCOUNT_ID;
37+
}
38+
if (requiresExplicitMatrixDefaultAccount(cfg)) {
39+
return false;
40+
}
41+
return normalizeAccountId(resolveMatrixDefaultOrOnlyAccountId(cfg)) === normalizedAccountId;
42+
}
43+
44+
function resolveLegacyMigrationSourcePath(
45+
env: NodeJS.ProcessEnv,
46+
accountId?: string | null,
47+
): string | null {
48+
if (!shouldReadLegacyCredentialsForAccount(accountId)) {
49+
return null;
50+
}
51+
const legacyPath = resolveLegacyMatrixCredentialsPath(env);
52+
return legacyPath === resolveMatrixCredentialsPath(env, accountId) ? null : legacyPath;
53+
}
54+
55+
function parseMatrixCredentialsFile(filePath: string): MatrixStoredCredentials | null {
56+
const raw = fs.readFileSync(filePath, "utf-8");
57+
const parsed = JSON.parse(raw) as Partial<MatrixStoredCredentials>;
58+
if (
59+
typeof parsed.homeserver !== "string" ||
60+
typeof parsed.userId !== "string" ||
61+
typeof parsed.accessToken !== "string"
62+
) {
63+
return null;
64+
}
65+
return parsed as MatrixStoredCredentials;
66+
}
67+
68+
export function resolveMatrixCredentialsDir(
69+
env: NodeJS.ProcessEnv = process.env,
70+
stateDir?: string,
71+
): string {
72+
const resolvedStateDir = stateDir ?? resolveStateDir(env);
73+
return resolveSharedMatrixCredentialsDir(resolvedStateDir);
74+
}
75+
76+
export function resolveMatrixCredentialsPath(
77+
env: NodeJS.ProcessEnv = process.env,
78+
accountId?: string | null,
79+
): string {
80+
const resolvedStateDir = resolveStateDir(env);
81+
return resolveSharedMatrixCredentialsPath({ stateDir: resolvedStateDir, accountId });
82+
}
83+
84+
export function loadMatrixCredentials(
85+
env: NodeJS.ProcessEnv = process.env,
86+
accountId?: string | null,
87+
): MatrixStoredCredentials | null {
88+
const credPath = resolveMatrixCredentialsPath(env, accountId);
89+
try {
90+
if (fs.existsSync(credPath)) {
91+
return parseMatrixCredentialsFile(credPath);
92+
}
93+
94+
const legacyPath = resolveLegacyMigrationSourcePath(env, accountId);
95+
if (!legacyPath || !fs.existsSync(legacyPath)) {
96+
return null;
97+
}
98+
99+
const parsed = parseMatrixCredentialsFile(legacyPath);
100+
if (!parsed) {
101+
return null;
102+
}
103+
104+
try {
105+
fs.mkdirSync(path.dirname(credPath), { recursive: true });
106+
fs.renameSync(legacyPath, credPath);
107+
} catch {
108+
// Keep returning the legacy credentials even if migration fails.
109+
}
110+
111+
return parsed;
112+
} catch {
113+
return null;
114+
}
115+
}
116+
117+
export function clearMatrixCredentials(
118+
env: NodeJS.ProcessEnv = process.env,
119+
accountId?: string | null,
120+
): void {
121+
const paths = [
122+
resolveMatrixCredentialsPath(env, accountId),
123+
resolveLegacyMigrationSourcePath(env, accountId),
124+
];
125+
for (const filePath of paths) {
126+
if (!filePath) {
127+
continue;
128+
}
129+
try {
130+
if (fs.existsSync(filePath)) {
131+
fs.unlinkSync(filePath);
132+
}
133+
} catch {
134+
// ignore
135+
}
136+
}
137+
}
138+
139+
export function credentialsMatchConfig(
140+
stored: MatrixStoredCredentials,
141+
config: { homeserver: string; userId: string; accessToken?: string },
142+
): boolean {
143+
if (!config.userId) {
144+
if (!config.accessToken) {
145+
return false;
146+
}
147+
return stored.homeserver === config.homeserver && stored.accessToken === config.accessToken;
148+
}
149+
return stored.homeserver === config.homeserver && stored.userId === config.userId;
150+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import type {
2+
saveMatrixCredentials as saveMatrixCredentialsType,
3+
touchMatrixCredentials as touchMatrixCredentialsType,
4+
} from "./credentials.js";
5+
6+
export async function saveMatrixCredentials(
7+
...args: Parameters<typeof saveMatrixCredentialsType>
8+
): ReturnType<typeof saveMatrixCredentialsType> {
9+
const runtime = await import("./credentials.js");
10+
return runtime.saveMatrixCredentials(...args);
11+
}
12+
13+
export async function touchMatrixCredentials(
14+
...args: Parameters<typeof touchMatrixCredentialsType>
15+
): ReturnType<typeof touchMatrixCredentialsType> {
16+
const runtime = await import("./credentials.js");
17+
return runtime.touchMatrixCredentials(...args);
18+
}

0 commit comments

Comments
 (0)