badgerclaw 0.1.7 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of badgerclaw might be problematic. Click here for more details.

Files changed (105) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/SETUP.md +291 -0
  3. package/index.ts +47 -0
  4. package/openclaw.plugin.json +1 -0
  5. package/package.json +32 -34
  6. package/scripts/postinstall.js +34 -0
  7. package/src/actions.ts +195 -0
  8. package/src/channel.ts +461 -0
  9. package/src/config-schema.ts +62 -0
  10. package/src/connect.ts +17 -0
  11. package/src/directory-live.ts +209 -0
  12. package/src/group-mentions.ts +103 -0
  13. package/src/matrix/accounts.ts +114 -0
  14. package/src/matrix/actions/client.ts +47 -0
  15. package/src/matrix/actions/limits.ts +6 -0
  16. package/src/matrix/actions/messages.ts +126 -0
  17. package/src/matrix/actions/pins.ts +84 -0
  18. package/src/matrix/actions/reactions.ts +102 -0
  19. package/src/matrix/actions/room.ts +85 -0
  20. package/src/matrix/actions/summary.ts +75 -0
  21. package/src/matrix/actions/types.ts +85 -0
  22. package/src/matrix/actions.ts +15 -0
  23. package/src/matrix/active-client.ts +32 -0
  24. package/src/matrix/client/backup.ts +91 -0
  25. package/src/matrix/client/config.ts +274 -0
  26. package/src/matrix/client/create-client.ts +125 -0
  27. package/src/matrix/client/logging.ts +46 -0
  28. package/src/matrix/client/runtime.ts +4 -0
  29. package/src/matrix/client/shared.ts +223 -0
  30. package/src/matrix/client/startup.ts +29 -0
  31. package/src/matrix/client/storage.ts +131 -0
  32. package/src/matrix/client/types.ts +34 -0
  33. package/src/matrix/client-bootstrap.ts +47 -0
  34. package/src/matrix/client.ts +14 -0
  35. package/src/matrix/credentials.ts +125 -0
  36. package/src/matrix/deps.ts +126 -0
  37. package/src/matrix/format.ts +22 -0
  38. package/src/matrix/index.ts +11 -0
  39. package/src/matrix/monitor/access-policy.ts +126 -0
  40. package/src/matrix/monitor/allowlist.ts +94 -0
  41. package/src/matrix/monitor/auto-join.ts +126 -0
  42. package/src/matrix/monitor/bot-commands.ts +431 -0
  43. package/src/matrix/monitor/chat-history.ts +75 -0
  44. package/src/matrix/monitor/direct.ts +152 -0
  45. package/src/matrix/monitor/events.ts +250 -0
  46. package/src/matrix/monitor/handler.ts +847 -0
  47. package/src/matrix/monitor/inbound-body.ts +28 -0
  48. package/src/matrix/monitor/index.ts +414 -0
  49. package/src/matrix/monitor/location.ts +100 -0
  50. package/src/matrix/monitor/media.ts +118 -0
  51. package/src/matrix/monitor/mentions.ts +62 -0
  52. package/src/matrix/monitor/replies.ts +124 -0
  53. package/src/matrix/monitor/room-info.ts +55 -0
  54. package/src/matrix/monitor/rooms.ts +47 -0
  55. package/src/matrix/monitor/threads.ts +68 -0
  56. package/src/matrix/monitor/types.ts +39 -0
  57. package/src/matrix/poll-types.ts +167 -0
  58. package/src/matrix/probe.ts +69 -0
  59. package/src/matrix/sdk-runtime.ts +18 -0
  60. package/src/matrix/send/client.ts +99 -0
  61. package/src/matrix/send/formatting.ts +93 -0
  62. package/src/matrix/send/media.ts +230 -0
  63. package/src/matrix/send/targets.ts +150 -0
  64. package/src/matrix/send/types.ts +110 -0
  65. package/src/matrix/send-queue.ts +28 -0
  66. package/src/matrix/send.ts +267 -0
  67. package/src/onboarding.ts +350 -0
  68. package/src/outbound.ts +58 -0
  69. package/src/resolve-targets.ts +125 -0
  70. package/src/runtime.ts +6 -0
  71. package/src/secret-input.ts +13 -0
  72. package/src/test-mocks.ts +53 -0
  73. package/src/tool-actions.ts +164 -0
  74. package/src/types.ts +121 -0
  75. package/README.md +0 -32
  76. package/dist/commands/autopair.d.ts +0 -3
  77. package/dist/commands/autopair.js +0 -102
  78. package/dist/commands/autopair.js.map +0 -1
  79. package/dist/commands/bot.d.ts +0 -2
  80. package/dist/commands/bot.js +0 -94
  81. package/dist/commands/bot.js.map +0 -1
  82. package/dist/commands/login.d.ts +0 -2
  83. package/dist/commands/login.js +0 -88
  84. package/dist/commands/login.js.map +0 -1
  85. package/dist/commands/logout.d.ts +0 -2
  86. package/dist/commands/logout.js +0 -36
  87. package/dist/commands/logout.js.map +0 -1
  88. package/dist/commands/status.d.ts +0 -2
  89. package/dist/commands/status.js +0 -23
  90. package/dist/commands/status.js.map +0 -1
  91. package/dist/commands/watch.d.ts +0 -2
  92. package/dist/commands/watch.js +0 -29
  93. package/dist/commands/watch.js.map +0 -1
  94. package/dist/index.d.ts +0 -2
  95. package/dist/index.js +0 -23
  96. package/dist/index.js.map +0 -1
  97. package/dist/lib/api.d.ts +0 -4
  98. package/dist/lib/api.js +0 -37
  99. package/dist/lib/api.js.map +0 -1
  100. package/dist/lib/auth.d.ts +0 -11
  101. package/dist/lib/auth.js +0 -48
  102. package/dist/lib/auth.js.map +0 -1
  103. package/dist/lib/pkce.d.ts +0 -2
  104. package/dist/lib/pkce.js +0 -15
  105. package/dist/lib/pkce.js.map +0 -1
@@ -0,0 +1,84 @@
1
+ import { resolveMatrixRoomId } from "../send.js";
2
+ import { resolveActionClient } from "./client.js";
3
+ import { fetchEventSummary, readPinnedEvents } from "./summary.js";
4
+ import {
5
+ EventType,
6
+ type MatrixActionClientOpts,
7
+ type MatrixActionClient,
8
+ type MatrixMessageSummary,
9
+ type RoomPinnedEventsEventContent,
10
+ } from "./types.js";
11
+
12
+ type ActionClient = MatrixActionClient["client"];
13
+
14
+ async function withResolvedPinRoom<T>(
15
+ roomId: string,
16
+ opts: MatrixActionClientOpts,
17
+ run: (client: ActionClient, resolvedRoom: string) => Promise<T>,
18
+ ): Promise<T> {
19
+ const { client, stopOnDone } = await resolveActionClient(opts);
20
+ try {
21
+ const resolvedRoom = await resolveMatrixRoomId(client, roomId);
22
+ return await run(client, resolvedRoom);
23
+ } finally {
24
+ if (stopOnDone) {
25
+ client.stop();
26
+ }
27
+ }
28
+ }
29
+
30
+ async function updateMatrixPins(
31
+ roomId: string,
32
+ messageId: string,
33
+ opts: MatrixActionClientOpts,
34
+ update: (current: string[]) => string[],
35
+ ): Promise<{ pinned: string[] }> {
36
+ return await withResolvedPinRoom(roomId, opts, async (client, resolvedRoom) => {
37
+ const current = await readPinnedEvents(client, resolvedRoom);
38
+ const next = update(current);
39
+ const payload: RoomPinnedEventsEventContent = { pinned: next };
40
+ await client.sendStateEvent(resolvedRoom, EventType.RoomPinnedEvents, "", payload);
41
+ return { pinned: next };
42
+ });
43
+ }
44
+
45
+ export async function pinMatrixMessage(
46
+ roomId: string,
47
+ messageId: string,
48
+ opts: MatrixActionClientOpts = {},
49
+ ): Promise<{ pinned: string[] }> {
50
+ return await updateMatrixPins(roomId, messageId, opts, (current) =>
51
+ current.includes(messageId) ? current : [...current, messageId],
52
+ );
53
+ }
54
+
55
+ export async function unpinMatrixMessage(
56
+ roomId: string,
57
+ messageId: string,
58
+ opts: MatrixActionClientOpts = {},
59
+ ): Promise<{ pinned: string[] }> {
60
+ return await updateMatrixPins(roomId, messageId, opts, (current) =>
61
+ current.filter((id) => id !== messageId),
62
+ );
63
+ }
64
+
65
+ export async function listMatrixPins(
66
+ roomId: string,
67
+ opts: MatrixActionClientOpts = {},
68
+ ): Promise<{ pinned: string[]; events: MatrixMessageSummary[] }> {
69
+ return await withResolvedPinRoom(roomId, opts, async (client, resolvedRoom) => {
70
+ const pinned = await readPinnedEvents(client, resolvedRoom);
71
+ const events = (
72
+ await Promise.all(
73
+ pinned.map(async (eventId) => {
74
+ try {
75
+ return await fetchEventSummary(client, resolvedRoom, eventId);
76
+ } catch {
77
+ return null;
78
+ }
79
+ }),
80
+ )
81
+ ).filter((event): event is MatrixMessageSummary => Boolean(event));
82
+ return { pinned, events };
83
+ });
84
+ }
@@ -0,0 +1,102 @@
1
+ import { resolveMatrixRoomId } from "../send.js";
2
+ import { resolveActionClient } from "./client.js";
3
+ import { resolveMatrixActionLimit } from "./limits.js";
4
+ import {
5
+ EventType,
6
+ RelationType,
7
+ type MatrixActionClientOpts,
8
+ type MatrixRawEvent,
9
+ type MatrixReactionSummary,
10
+ type ReactionEventContent,
11
+ } from "./types.js";
12
+
13
+ function getReactionsPath(roomId: string, messageId: string): string {
14
+ return `/_matrix/client/v1/rooms/${encodeURIComponent(roomId)}/relations/${encodeURIComponent(messageId)}/${RelationType.Annotation}/${EventType.Reaction}`;
15
+ }
16
+
17
+ async function listReactionEvents(
18
+ client: NonNullable<MatrixActionClientOpts["client"]>,
19
+ roomId: string,
20
+ messageId: string,
21
+ limit: number,
22
+ ): Promise<MatrixRawEvent[]> {
23
+ const res = (await client.doRequest("GET", getReactionsPath(roomId, messageId), {
24
+ dir: "b",
25
+ limit,
26
+ })) as { chunk: MatrixRawEvent[] };
27
+ return res.chunk;
28
+ }
29
+
30
+ export async function listMatrixReactions(
31
+ roomId: string,
32
+ messageId: string,
33
+ opts: MatrixActionClientOpts & { limit?: number } = {},
34
+ ): Promise<MatrixReactionSummary[]> {
35
+ const { client, stopOnDone } = await resolveActionClient(opts);
36
+ try {
37
+ const resolvedRoom = await resolveMatrixRoomId(client, roomId);
38
+ const limit = resolveMatrixActionLimit(opts.limit, 100);
39
+ const chunk = await listReactionEvents(client, resolvedRoom, messageId, limit);
40
+ const summaries = new Map<string, MatrixReactionSummary>();
41
+ for (const event of chunk) {
42
+ const content = event.content as ReactionEventContent;
43
+ const key = content["m.relates_to"]?.key;
44
+ if (!key) {
45
+ continue;
46
+ }
47
+ const sender = event.sender ?? "";
48
+ const entry: MatrixReactionSummary = summaries.get(key) ?? {
49
+ key,
50
+ count: 0,
51
+ users: [],
52
+ };
53
+ entry.count += 1;
54
+ if (sender && !entry.users.includes(sender)) {
55
+ entry.users.push(sender);
56
+ }
57
+ summaries.set(key, entry);
58
+ }
59
+ return Array.from(summaries.values());
60
+ } finally {
61
+ if (stopOnDone) {
62
+ client.stop();
63
+ }
64
+ }
65
+ }
66
+
67
+ export async function removeMatrixReactions(
68
+ roomId: string,
69
+ messageId: string,
70
+ opts: MatrixActionClientOpts & { emoji?: string } = {},
71
+ ): Promise<{ removed: number }> {
72
+ const { client, stopOnDone } = await resolveActionClient(opts);
73
+ try {
74
+ const resolvedRoom = await resolveMatrixRoomId(client, roomId);
75
+ const chunk = await listReactionEvents(client, resolvedRoom, messageId, 200);
76
+ const userId = await client.getUserId();
77
+ if (!userId) {
78
+ return { removed: 0 };
79
+ }
80
+ const targetEmoji = opts.emoji?.trim();
81
+ const toRemove = chunk
82
+ .filter((event) => event.sender === userId)
83
+ .filter((event) => {
84
+ if (!targetEmoji) {
85
+ return true;
86
+ }
87
+ const content = event.content as ReactionEventContent;
88
+ return content["m.relates_to"]?.key === targetEmoji;
89
+ })
90
+ .map((event) => event.event_id)
91
+ .filter((id): id is string => Boolean(id));
92
+ if (toRemove.length === 0) {
93
+ return { removed: 0 };
94
+ }
95
+ await Promise.all(toRemove.map((id) => client.redactEvent(resolvedRoom, id)));
96
+ return { removed: toRemove.length };
97
+ } finally {
98
+ if (stopOnDone) {
99
+ client.stop();
100
+ }
101
+ }
102
+ }
@@ -0,0 +1,85 @@
1
+ import { resolveMatrixRoomId } from "../send.js";
2
+ import { resolveActionClient } from "./client.js";
3
+ import { EventType, type MatrixActionClientOpts } from "./types.js";
4
+
5
+ export async function getMatrixMemberInfo(
6
+ userId: string,
7
+ opts: MatrixActionClientOpts & { roomId?: string } = {},
8
+ ) {
9
+ const { client, stopOnDone } = await resolveActionClient(opts);
10
+ try {
11
+ const roomId = opts.roomId ? await resolveMatrixRoomId(client, opts.roomId) : undefined;
12
+ // @vector-im/matrix-bot-sdk uses getUserProfile
13
+ const profile = await client.getUserProfile(userId);
14
+ // Note: @vector-im/matrix-bot-sdk doesn't have getRoom().getMember() like matrix-js-sdk
15
+ // We'd need to fetch room state separately if needed
16
+ return {
17
+ userId,
18
+ profile: {
19
+ displayName: profile?.displayname ?? null,
20
+ avatarUrl: profile?.avatar_url ?? null,
21
+ },
22
+ membership: null, // Would need separate room state query
23
+ powerLevel: null, // Would need separate power levels state query
24
+ displayName: profile?.displayname ?? null,
25
+ roomId: roomId ?? null,
26
+ };
27
+ } finally {
28
+ if (stopOnDone) {
29
+ client.stop();
30
+ }
31
+ }
32
+ }
33
+
34
+ export async function getMatrixRoomInfo(roomId: string, opts: MatrixActionClientOpts = {}) {
35
+ const { client, stopOnDone } = await resolveActionClient(opts);
36
+ try {
37
+ const resolvedRoom = await resolveMatrixRoomId(client, roomId);
38
+ // @vector-im/matrix-bot-sdk uses getRoomState for state events
39
+ let name: string | null = null;
40
+ let topic: string | null = null;
41
+ let canonicalAlias: string | null = null;
42
+ let memberCount: number | null = null;
43
+
44
+ try {
45
+ const nameState = await client.getRoomStateEvent(resolvedRoom, "m.room.name", "");
46
+ name = nameState?.name ?? null;
47
+ } catch {
48
+ // ignore
49
+ }
50
+
51
+ try {
52
+ const topicState = await client.getRoomStateEvent(resolvedRoom, EventType.RoomTopic, "");
53
+ topic = topicState?.topic ?? null;
54
+ } catch {
55
+ // ignore
56
+ }
57
+
58
+ try {
59
+ const aliasState = await client.getRoomStateEvent(resolvedRoom, "m.room.canonical_alias", "");
60
+ canonicalAlias = aliasState?.alias ?? null;
61
+ } catch {
62
+ // ignore
63
+ }
64
+
65
+ try {
66
+ const members = await client.getJoinedRoomMembers(resolvedRoom);
67
+ memberCount = members.length;
68
+ } catch {
69
+ // ignore
70
+ }
71
+
72
+ return {
73
+ roomId: resolvedRoom,
74
+ name,
75
+ topic,
76
+ canonicalAlias,
77
+ altAliases: [], // Would need separate query
78
+ memberCount,
79
+ };
80
+ } finally {
81
+ if (stopOnDone) {
82
+ client.stop();
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,75 @@
1
+ import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2
+ import {
3
+ EventType,
4
+ type MatrixMessageSummary,
5
+ type MatrixRawEvent,
6
+ type RoomMessageEventContent,
7
+ type RoomPinnedEventsEventContent,
8
+ } from "./types.js";
9
+
10
+ export function summarizeMatrixRawEvent(event: MatrixRawEvent): MatrixMessageSummary {
11
+ const content = event.content as RoomMessageEventContent;
12
+ const relates = content["m.relates_to"];
13
+ let relType: string | undefined;
14
+ let eventId: string | undefined;
15
+ if (relates) {
16
+ if ("rel_type" in relates) {
17
+ relType = relates.rel_type;
18
+ eventId = relates.event_id;
19
+ } else if ("m.in_reply_to" in relates) {
20
+ eventId = relates["m.in_reply_to"]?.event_id;
21
+ }
22
+ }
23
+ const relatesTo =
24
+ relType || eventId
25
+ ? {
26
+ relType,
27
+ eventId,
28
+ }
29
+ : undefined;
30
+ return {
31
+ eventId: event.event_id,
32
+ sender: event.sender,
33
+ body: content.body,
34
+ msgtype: content.msgtype,
35
+ timestamp: event.origin_server_ts,
36
+ relatesTo,
37
+ };
38
+ }
39
+
40
+ export async function readPinnedEvents(client: MatrixClient, roomId: string): Promise<string[]> {
41
+ try {
42
+ const content = (await client.getRoomStateEvent(
43
+ roomId,
44
+ EventType.RoomPinnedEvents,
45
+ "",
46
+ )) as RoomPinnedEventsEventContent;
47
+ const pinned = content.pinned;
48
+ return pinned.filter((id) => id.trim().length > 0);
49
+ } catch (err: unknown) {
50
+ const errObj = err as { statusCode?: number; body?: { errcode?: string } };
51
+ const httpStatus = errObj.statusCode;
52
+ const errcode = errObj.body?.errcode;
53
+ if (httpStatus === 404 || errcode === "M_NOT_FOUND") {
54
+ return [];
55
+ }
56
+ throw err;
57
+ }
58
+ }
59
+
60
+ export async function fetchEventSummary(
61
+ client: MatrixClient,
62
+ roomId: string,
63
+ eventId: string,
64
+ ): Promise<MatrixMessageSummary | null> {
65
+ try {
66
+ const raw = (await client.getEvent(roomId, eventId)) as unknown as MatrixRawEvent;
67
+ if (raw.unsigned?.redacted_because) {
68
+ return null;
69
+ }
70
+ return summarizeMatrixRawEvent(raw);
71
+ } catch {
72
+ // Event not found, redacted, or inaccessible - return null
73
+ return null;
74
+ }
75
+ }
@@ -0,0 +1,85 @@
1
+ import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2
+
3
+ export const MsgType = {
4
+ Text: "m.text",
5
+ } as const;
6
+
7
+ export const RelationType = {
8
+ Replace: "m.replace",
9
+ Annotation: "m.annotation",
10
+ } as const;
11
+
12
+ export const EventType = {
13
+ RoomMessage: "m.room.message",
14
+ RoomPinnedEvents: "m.room.pinned_events",
15
+ RoomTopic: "m.room.topic",
16
+ Reaction: "m.reaction",
17
+ } as const;
18
+
19
+ export type RoomMessageEventContent = {
20
+ msgtype: string;
21
+ body: string;
22
+ "m.new_content"?: RoomMessageEventContent;
23
+ "m.relates_to"?: {
24
+ rel_type?: string;
25
+ event_id?: string;
26
+ "m.in_reply_to"?: { event_id?: string };
27
+ };
28
+ };
29
+
30
+ export type ReactionEventContent = {
31
+ "m.relates_to": {
32
+ rel_type: string;
33
+ event_id: string;
34
+ key: string;
35
+ };
36
+ };
37
+
38
+ export type RoomPinnedEventsEventContent = {
39
+ pinned: string[];
40
+ };
41
+
42
+ export type RoomTopicEventContent = {
43
+ topic?: string;
44
+ };
45
+
46
+ export type MatrixRawEvent = {
47
+ event_id: string;
48
+ sender: string;
49
+ type: string;
50
+ origin_server_ts: number;
51
+ content: Record<string, unknown>;
52
+ unsigned?: {
53
+ redacted_because?: unknown;
54
+ };
55
+ };
56
+
57
+ export type MatrixActionClientOpts = {
58
+ client?: MatrixClient;
59
+ timeoutMs?: number;
60
+ accountId?: string | null;
61
+ };
62
+
63
+ export type MatrixMessageSummary = {
64
+ eventId?: string;
65
+ sender?: string;
66
+ body?: string;
67
+ msgtype?: string;
68
+ timestamp?: number;
69
+ relatesTo?: {
70
+ relType?: string;
71
+ eventId?: string;
72
+ key?: string;
73
+ };
74
+ };
75
+
76
+ export type MatrixReactionSummary = {
77
+ key: string;
78
+ count: number;
79
+ users: string[];
80
+ };
81
+
82
+ export type MatrixActionClient = {
83
+ client: MatrixClient;
84
+ stopOnDone: boolean;
85
+ };
@@ -0,0 +1,15 @@
1
+ export type {
2
+ MatrixActionClientOpts,
3
+ MatrixMessageSummary,
4
+ MatrixReactionSummary,
5
+ } from "./actions/types.js";
6
+ export {
7
+ sendMatrixMessage,
8
+ editMatrixMessage,
9
+ deleteMatrixMessage,
10
+ readMatrixMessages,
11
+ } from "./actions/messages.js";
12
+ export { listMatrixReactions, removeMatrixReactions } from "./actions/reactions.js";
13
+ export { pinMatrixMessage, unpinMatrixMessage, listMatrixPins } from "./actions/pins.js";
14
+ export { getMatrixMemberInfo, getMatrixRoomInfo } from "./actions/room.js";
15
+ export { reactMatrixMessage } from "./send.js";
@@ -0,0 +1,32 @@
1
+ import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2
+ import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
3
+
4
+ // Support multiple active clients for multi-account
5
+ const activeClients = new Map<string, MatrixClient>();
6
+
7
+ export function setActiveMatrixClient(
8
+ client: MatrixClient | null,
9
+ accountId?: string | null,
10
+ ): void {
11
+ const key = normalizeAccountId(accountId);
12
+ if (client) {
13
+ activeClients.set(key, client);
14
+ } else {
15
+ activeClients.delete(key);
16
+ }
17
+ }
18
+
19
+ export function getActiveMatrixClient(accountId?: string | null): MatrixClient | null {
20
+ const key = normalizeAccountId(accountId);
21
+ return activeClients.get(key) ?? null;
22
+ }
23
+
24
+ export function getAnyActiveMatrixClient(): MatrixClient | null {
25
+ // Return any available client (for backward compatibility)
26
+ const first = activeClients.values().next();
27
+ return first.done ? null : first.value;
28
+ }
29
+
30
+ export function clearAllActiveMatrixClients(): void {
31
+ activeClients.clear();
32
+ }
@@ -0,0 +1,91 @@
1
+ import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2
+ import { appendFileSync, writeFileSync, mkdirSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { generateKeyPairSync } from "node:crypto";
6
+ import { getMatrixLogService } from "../sdk-runtime.js";
7
+
8
+ export type KeyBackupStatus = {
9
+ enabled: boolean;
10
+ version: string | null;
11
+ deviceId: string | null;
12
+ };
13
+
14
+ export async function getEncryptionKeyBackupStatus(client: MatrixClient): Promise<KeyBackupStatus> {
15
+ const LogService = getMatrixLogService();
16
+ try {
17
+ const backupInfo = await client.getKeyBackupVersion();
18
+ const whoami = await client.getWhoAmI();
19
+ return { enabled: backupInfo !== null, version: backupInfo?.version ?? null, deviceId: whoami.device_id ?? null };
20
+ } catch (err) {
21
+ LogService.warn("MatrixKeyBackup", "Failed to check key backup status:", err);
22
+ return { enabled: false, version: null, deviceId: null };
23
+ }
24
+ }
25
+
26
+ export async function setupKeyBackup(client: MatrixClient): Promise<void> {
27
+ const LogService = getMatrixLogService();
28
+
29
+ let deviceId = "(unknown)";
30
+ try { deviceId = (await client.getWhoAmI()).device_id ?? deviceId; } catch { /* non-fatal */ }
31
+
32
+ LogService.info("MatrixKeyBackup", `Crypto ready — device ID: ${deviceId}`);
33
+
34
+ if (!client.crypto) {
35
+ LogService.info("MatrixKeyBackup", "Crypto not available, skipping backup setup");
36
+ return;
37
+ }
38
+
39
+ try {
40
+ let backupInfo = await client.getKeyBackupVersion();
41
+
42
+ if (!backupInfo) {
43
+ LogService.info("MatrixKeyBackup", "No backup found — generating Curve25519 key pair and creating backup version");
44
+
45
+ // Generate X25519 (Curve25519) key pair using Node crypto
46
+ const { publicKey: pubKeyObj, privateKey: privKeyObj } = generateKeyPairSync("x25519");
47
+ const pubKeyRaw = pubKeyObj.export({ type: "spki", format: "der" }).slice(-32);
48
+ const privKeyRaw = privKeyObj.export({ type: "pkcs8", format: "der" }).slice(-32);
49
+ const publicKeyBase64 = pubKeyRaw.toString("base64");
50
+ const privateKeyBase64 = privKeyRaw.toString("base64");
51
+
52
+ // Create the backup version on the server
53
+ await client.signAndCreateKeyBackupVersion({
54
+ algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
55
+ auth_data: { public_key: publicKeyBase64 },
56
+ } as any);
57
+
58
+ // Save private key for cross-device restore
59
+ const backupDir = join(homedir(), ".openclaw", "backup");
60
+ mkdirSync(backupDir, { recursive: true });
61
+ writeFileSync(
62
+ join(backupDir, `private-key-${deviceId}.json`),
63
+ JSON.stringify({ privateKey: privateKeyBase64, deviceId, created: new Date().toISOString() }),
64
+ { mode: 0o600 }
65
+ );
66
+
67
+ backupInfo = await client.getKeyBackupVersion();
68
+ LogService.info("MatrixKeyBackup", `Created backup version ${backupInfo?.version}`);
69
+ }
70
+
71
+ if (!backupInfo) {
72
+ LogService.warn("MatrixKeyBackup", "No backup info after creation attempt");
73
+ return;
74
+ }
75
+
76
+ await client.crypto.enableKeyBackup(backupInfo);
77
+ LogService.info("MatrixKeyBackup", `Backup enabled v${backupInfo.version} on ${deviceId} — uploading room keys`);
78
+ _persistRecord(backupInfo.version, deviceId);
79
+ } catch (err) {
80
+ LogService.warn("MatrixKeyBackup", "Backup setup failed:", err);
81
+ }
82
+ }
83
+
84
+ function _persistRecord(version: string, deviceId: string): void {
85
+ try {
86
+ const dir = join(homedir(), ".openclaw", "backup");
87
+ mkdirSync(dir, { recursive: true });
88
+ appendFileSync(join(dir, "key-backup-record.log"),
89
+ JSON.stringify({ version, deviceId, timestamp: new Date().toISOString() }) + "\n");
90
+ } catch { /* non-fatal */ }
91
+ }