@badgerclaw/connect 1.0.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.
Files changed (70) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/SETUP.md +131 -0
  3. package/index.ts +23 -0
  4. package/openclaw.plugin.json +1 -0
  5. package/package.json +32 -0
  6. package/src/actions.ts +195 -0
  7. package/src/channel.ts +461 -0
  8. package/src/config-schema.ts +62 -0
  9. package/src/connect.ts +17 -0
  10. package/src/directory-live.ts +209 -0
  11. package/src/group-mentions.ts +52 -0
  12. package/src/matrix/accounts.ts +114 -0
  13. package/src/matrix/actions/client.ts +47 -0
  14. package/src/matrix/actions/limits.ts +6 -0
  15. package/src/matrix/actions/messages.ts +126 -0
  16. package/src/matrix/actions/pins.ts +84 -0
  17. package/src/matrix/actions/reactions.ts +102 -0
  18. package/src/matrix/actions/room.ts +85 -0
  19. package/src/matrix/actions/summary.ts +75 -0
  20. package/src/matrix/actions/types.ts +85 -0
  21. package/src/matrix/actions.ts +15 -0
  22. package/src/matrix/active-client.ts +32 -0
  23. package/src/matrix/client/config.ts +245 -0
  24. package/src/matrix/client/create-client.ts +125 -0
  25. package/src/matrix/client/logging.ts +46 -0
  26. package/src/matrix/client/runtime.ts +4 -0
  27. package/src/matrix/client/shared.ts +210 -0
  28. package/src/matrix/client/startup.ts +29 -0
  29. package/src/matrix/client/storage.ts +131 -0
  30. package/src/matrix/client/types.ts +34 -0
  31. package/src/matrix/client-bootstrap.ts +47 -0
  32. package/src/matrix/client.ts +14 -0
  33. package/src/matrix/credentials.ts +125 -0
  34. package/src/matrix/deps.ts +126 -0
  35. package/src/matrix/format.ts +22 -0
  36. package/src/matrix/index.ts +11 -0
  37. package/src/matrix/monitor/access-policy.ts +126 -0
  38. package/src/matrix/monitor/allowlist.ts +94 -0
  39. package/src/matrix/monitor/auto-join.ts +72 -0
  40. package/src/matrix/monitor/direct.ts +152 -0
  41. package/src/matrix/monitor/events.ts +168 -0
  42. package/src/matrix/monitor/handler.ts +768 -0
  43. package/src/matrix/monitor/inbound-body.ts +28 -0
  44. package/src/matrix/monitor/index.ts +414 -0
  45. package/src/matrix/monitor/location.ts +100 -0
  46. package/src/matrix/monitor/media.ts +118 -0
  47. package/src/matrix/monitor/mentions.ts +62 -0
  48. package/src/matrix/monitor/replies.ts +124 -0
  49. package/src/matrix/monitor/room-info.ts +55 -0
  50. package/src/matrix/monitor/rooms.ts +47 -0
  51. package/src/matrix/monitor/threads.ts +68 -0
  52. package/src/matrix/monitor/types.ts +39 -0
  53. package/src/matrix/poll-types.ts +167 -0
  54. package/src/matrix/probe.ts +69 -0
  55. package/src/matrix/sdk-runtime.ts +18 -0
  56. package/src/matrix/send/client.ts +99 -0
  57. package/src/matrix/send/formatting.ts +93 -0
  58. package/src/matrix/send/media.ts +230 -0
  59. package/src/matrix/send/targets.ts +150 -0
  60. package/src/matrix/send/types.ts +110 -0
  61. package/src/matrix/send-queue.ts +28 -0
  62. package/src/matrix/send.ts +267 -0
  63. package/src/onboarding.ts +331 -0
  64. package/src/outbound.ts +58 -0
  65. package/src/resolve-targets.ts +125 -0
  66. package/src/runtime.ts +6 -0
  67. package/src/secret-input.ts +13 -0
  68. package/src/test-mocks.ts +53 -0
  69. package/src/tool-actions.ts +164 -0
  70. package/src/types.ts +118 -0
@@ -0,0 +1,125 @@
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 { getMatrixRuntime } from "../runtime.js";
6
+
7
+ export type MatrixStoredCredentials = {
8
+ homeserver: string;
9
+ userId: string;
10
+ accessToken: string;
11
+ deviceId?: string;
12
+ createdAt: string;
13
+ lastUsedAt?: string;
14
+ };
15
+
16
+ function credentialsFilename(accountId?: string | null): string {
17
+ const normalized = normalizeAccountId(accountId);
18
+ if (normalized === DEFAULT_ACCOUNT_ID) {
19
+ return "credentials.json";
20
+ }
21
+ // normalizeAccountId produces lowercase [a-z0-9-] strings, already filesystem-safe.
22
+ // Different raw IDs that normalize to the same value are the same logical account.
23
+ return `credentials-${normalized}.json`;
24
+ }
25
+
26
+ export function resolveMatrixCredentialsDir(
27
+ env: NodeJS.ProcessEnv = process.env,
28
+ stateDir?: string,
29
+ ): string {
30
+ const resolvedStateDir = stateDir ?? getMatrixRuntime().state.resolveStateDir(env, os.homedir);
31
+ return path.join(resolvedStateDir, "credentials", "badgerclaw");
32
+ }
33
+
34
+ export function resolveMatrixCredentialsPath(
35
+ env: NodeJS.ProcessEnv = process.env,
36
+ accountId?: string | null,
37
+ ): string {
38
+ const dir = resolveMatrixCredentialsDir(env);
39
+ return path.join(dir, credentialsFilename(accountId));
40
+ }
41
+
42
+ export function loadMatrixCredentials(
43
+ env: NodeJS.ProcessEnv = process.env,
44
+ accountId?: string | null,
45
+ ): MatrixStoredCredentials | null {
46
+ const credPath = resolveMatrixCredentialsPath(env, accountId);
47
+ try {
48
+ if (!fs.existsSync(credPath)) {
49
+ return null;
50
+ }
51
+ const raw = fs.readFileSync(credPath, "utf-8");
52
+ const parsed = JSON.parse(raw) as Partial<MatrixStoredCredentials>;
53
+ if (
54
+ typeof parsed.homeserver !== "string" ||
55
+ typeof parsed.userId !== "string" ||
56
+ typeof parsed.accessToken !== "string"
57
+ ) {
58
+ return null;
59
+ }
60
+ return parsed as MatrixStoredCredentials;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ export function saveMatrixCredentials(
67
+ credentials: Omit<MatrixStoredCredentials, "createdAt" | "lastUsedAt">,
68
+ env: NodeJS.ProcessEnv = process.env,
69
+ accountId?: string | null,
70
+ ): void {
71
+ const dir = resolveMatrixCredentialsDir(env);
72
+ fs.mkdirSync(dir, { recursive: true });
73
+
74
+ const credPath = resolveMatrixCredentialsPath(env, accountId);
75
+
76
+ const existing = loadMatrixCredentials(env, accountId);
77
+ const now = new Date().toISOString();
78
+
79
+ const toSave: MatrixStoredCredentials = {
80
+ ...credentials,
81
+ createdAt: existing?.createdAt ?? now,
82
+ lastUsedAt: now,
83
+ };
84
+
85
+ fs.writeFileSync(credPath, JSON.stringify(toSave, null, 2), "utf-8");
86
+ }
87
+
88
+ export function touchMatrixCredentials(
89
+ env: NodeJS.ProcessEnv = process.env,
90
+ accountId?: string | null,
91
+ ): void {
92
+ const existing = loadMatrixCredentials(env, accountId);
93
+ if (!existing) {
94
+ return;
95
+ }
96
+
97
+ existing.lastUsedAt = new Date().toISOString();
98
+ const credPath = resolveMatrixCredentialsPath(env, accountId);
99
+ fs.writeFileSync(credPath, JSON.stringify(existing, null, 2), "utf-8");
100
+ }
101
+
102
+ export function clearMatrixCredentials(
103
+ env: NodeJS.ProcessEnv = process.env,
104
+ accountId?: string | null,
105
+ ): void {
106
+ const credPath = resolveMatrixCredentialsPath(env, accountId);
107
+ try {
108
+ if (fs.existsSync(credPath)) {
109
+ fs.unlinkSync(credPath);
110
+ }
111
+ } catch {
112
+ // ignore
113
+ }
114
+ }
115
+
116
+ export function credentialsMatchConfig(
117
+ stored: MatrixStoredCredentials,
118
+ config: { homeserver: string; userId: string },
119
+ ): boolean {
120
+ // If userId is empty (token-based auth), only match homeserver
121
+ if (!config.userId) {
122
+ return stored.homeserver === config.homeserver;
123
+ }
124
+ return stored.homeserver === config.homeserver && stored.userId === config.userId;
125
+ }
@@ -0,0 +1,126 @@
1
+ import fs from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { runPluginCommandWithTimeout, type RuntimeEnv } from "openclaw/plugin-sdk/matrix";
6
+
7
+ const MATRIX_SDK_PACKAGE = "@vector-im/matrix-bot-sdk";
8
+ const MATRIX_CRYPTO_DOWNLOAD_HELPER = "@matrix-org/matrix-sdk-crypto-nodejs/download-lib.js";
9
+
10
+ function formatCommandError(result: { stderr: string; stdout: string }): string {
11
+ const stderr = result.stderr.trim();
12
+ if (stderr) {
13
+ return stderr;
14
+ }
15
+ const stdout = result.stdout.trim();
16
+ if (stdout) {
17
+ return stdout;
18
+ }
19
+ return "unknown error";
20
+ }
21
+
22
+ function isMissingMatrixCryptoRuntimeError(err: unknown): boolean {
23
+ const message = err instanceof Error ? err.message : String(err ?? "");
24
+ return (
25
+ message.includes("Cannot find module") &&
26
+ message.includes("@matrix-org/matrix-sdk-crypto-nodejs-")
27
+ );
28
+ }
29
+
30
+ export function isMatrixSdkAvailable(): boolean {
31
+ try {
32
+ const req = createRequire(import.meta.url);
33
+ req.resolve(MATRIX_SDK_PACKAGE);
34
+ return true;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ function resolvePluginRoot(): string {
41
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
42
+ return path.resolve(currentDir, "..", "..");
43
+ }
44
+
45
+ export async function ensureMatrixCryptoRuntime(
46
+ params: {
47
+ log?: (message: string) => void;
48
+ requireFn?: (id: string) => unknown;
49
+ resolveFn?: (id: string) => string;
50
+ runCommand?: typeof runPluginCommandWithTimeout;
51
+ nodeExecutable?: string;
52
+ } = {},
53
+ ): Promise<void> {
54
+ const req = createRequire(import.meta.url);
55
+ const requireFn = params.requireFn ?? ((id: string) => req(id));
56
+ const resolveFn = params.resolveFn ?? ((id: string) => req.resolve(id));
57
+ const runCommand = params.runCommand ?? runPluginCommandWithTimeout;
58
+ const nodeExecutable = params.nodeExecutable ?? process.execPath;
59
+
60
+ try {
61
+ requireFn(MATRIX_SDK_PACKAGE);
62
+ return;
63
+ } catch (err) {
64
+ if (!isMissingMatrixCryptoRuntimeError(err)) {
65
+ throw err;
66
+ }
67
+ }
68
+
69
+ const scriptPath = resolveFn(MATRIX_CRYPTO_DOWNLOAD_HELPER);
70
+ params.log?.("badgerclaw: crypto runtime missing; downloading platform library…");
71
+ const result = await runCommand({
72
+ argv: [nodeExecutable, scriptPath],
73
+ cwd: path.dirname(scriptPath),
74
+ timeoutMs: 300_000,
75
+ env: { COREPACK_ENABLE_DOWNLOAD_PROMPT: "0" },
76
+ });
77
+ if (result.code !== 0) {
78
+ throw new Error(`BadgerClaw crypto runtime bootstrap failed: ${formatCommandError(result)}`);
79
+ }
80
+
81
+ try {
82
+ requireFn(MATRIX_SDK_PACKAGE);
83
+ } catch (err) {
84
+ throw new Error(
85
+ `BadgerClaw crypto runtime remains unavailable after bootstrap: ${err instanceof Error ? err.message : String(err)}`,
86
+ );
87
+ }
88
+ }
89
+
90
+ export async function ensureMatrixSdkInstalled(params: {
91
+ runtime: RuntimeEnv;
92
+ confirm?: (message: string) => Promise<boolean>;
93
+ }): Promise<void> {
94
+ if (isMatrixSdkAvailable()) {
95
+ return;
96
+ }
97
+ const confirm = params.confirm;
98
+ if (confirm) {
99
+ const ok = await confirm("BadgerClaw requires @vector-im/matrix-bot-sdk. Install now?");
100
+ if (!ok) {
101
+ throw new Error("BadgerClaw requires @vector-im/matrix-bot-sdk (install dependencies first).");
102
+ }
103
+ }
104
+
105
+ const root = resolvePluginRoot();
106
+ const command = fs.existsSync(path.join(root, "pnpm-lock.yaml"))
107
+ ? ["pnpm", "install"]
108
+ : ["npm", "install", "--omit=dev", "--silent"];
109
+ params.runtime.log?.(`badgerclaw: installing dependencies via ${command[0]} (${root})…`);
110
+ const result = await runPluginCommandWithTimeout({
111
+ argv: command,
112
+ cwd: root,
113
+ timeoutMs: 300_000,
114
+ env: { COREPACK_ENABLE_DOWNLOAD_PROMPT: "0" },
115
+ });
116
+ if (result.code !== 0) {
117
+ throw new Error(
118
+ result.stderr.trim() || result.stdout.trim() || "BadgerClaw dependency install failed.",
119
+ );
120
+ }
121
+ if (!isMatrixSdkAvailable()) {
122
+ throw new Error(
123
+ "BadgerClaw dependency install completed but @vector-im/matrix-bot-sdk is still missing.",
124
+ );
125
+ }
126
+ }
@@ -0,0 +1,22 @@
1
+ import MarkdownIt from "markdown-it";
2
+
3
+ const md = new MarkdownIt({
4
+ html: false,
5
+ linkify: true,
6
+ breaks: true,
7
+ typographer: false,
8
+ });
9
+
10
+ md.enable("strikethrough");
11
+
12
+ const { escapeHtml } = md.utils;
13
+
14
+ md.renderer.rules.image = (tokens, idx) => escapeHtml(tokens[idx]?.content ?? "");
15
+
16
+ md.renderer.rules.html_block = (tokens, idx) => escapeHtml(tokens[idx]?.content ?? "");
17
+ md.renderer.rules.html_inline = (tokens, idx) => escapeHtml(tokens[idx]?.content ?? "");
18
+
19
+ export function markdownToMatrixHtml(markdown: string): string {
20
+ const rendered = md.render(markdown ?? "");
21
+ return rendered.trimEnd();
22
+ }
@@ -0,0 +1,11 @@
1
+ export { monitorMatrixProvider } from "./monitor/index.js";
2
+ export { probeMatrix } from "./probe.js";
3
+ export {
4
+ reactMatrixMessage,
5
+ resolveMatrixRoomId,
6
+ sendReadReceiptMatrix,
7
+ sendMessageMatrix,
8
+ sendPollMatrix,
9
+ sendTypingMatrix,
10
+ } from "./send.js";
11
+ export { resolveMatrixAuth, resolveSharedMatrixClient } from "./client.js";
@@ -0,0 +1,126 @@
1
+ import {
2
+ formatAllowlistMatchMeta,
3
+ issuePairingChallenge,
4
+ readStoreAllowFromForDmPolicy,
5
+ resolveDmGroupAccessWithLists,
6
+ resolveSenderScopedGroupPolicy,
7
+ } from "openclaw/plugin-sdk/matrix";
8
+ import {
9
+ normalizeMatrixAllowList,
10
+ resolveMatrixAllowListMatch,
11
+ resolveMatrixAllowListMatches,
12
+ } from "./allowlist.js";
13
+
14
+ type MatrixDmPolicy = "open" | "pairing" | "allowlist" | "disabled";
15
+ type MatrixGroupPolicy = "open" | "allowlist" | "disabled";
16
+
17
+ export async function resolveMatrixAccessState(params: {
18
+ isDirectMessage: boolean;
19
+ resolvedAccountId: string;
20
+ dmPolicy: MatrixDmPolicy;
21
+ groupPolicy: MatrixGroupPolicy;
22
+ allowFrom: string[];
23
+ groupAllowFrom: Array<string | number>;
24
+ senderId: string;
25
+ readStoreForDmPolicy: (provider: string, accountId: string) => Promise<string[]>;
26
+ }) {
27
+ const storeAllowFrom = params.isDirectMessage
28
+ ? await readStoreAllowFromForDmPolicy({
29
+ provider: "badgerclaw",
30
+ accountId: params.resolvedAccountId,
31
+ dmPolicy: params.dmPolicy,
32
+ readStore: params.readStoreForDmPolicy,
33
+ })
34
+ : [];
35
+ const normalizedGroupAllowFrom = normalizeMatrixAllowList(params.groupAllowFrom);
36
+ const senderGroupPolicy = resolveSenderScopedGroupPolicy({
37
+ groupPolicy: params.groupPolicy,
38
+ groupAllowFrom: normalizedGroupAllowFrom,
39
+ });
40
+ const access = resolveDmGroupAccessWithLists({
41
+ isGroup: !params.isDirectMessage,
42
+ dmPolicy: params.dmPolicy,
43
+ groupPolicy: senderGroupPolicy,
44
+ allowFrom: params.allowFrom,
45
+ groupAllowFrom: normalizedGroupAllowFrom,
46
+ storeAllowFrom,
47
+ groupAllowFromFallbackToAllowFrom: false,
48
+ isSenderAllowed: (allowFrom) =>
49
+ resolveMatrixAllowListMatches({
50
+ allowList: normalizeMatrixAllowList(allowFrom),
51
+ userId: params.senderId,
52
+ }),
53
+ });
54
+ const effectiveAllowFrom = normalizeMatrixAllowList(access.effectiveAllowFrom);
55
+ const effectiveGroupAllowFrom = normalizeMatrixAllowList(access.effectiveGroupAllowFrom);
56
+ return {
57
+ access,
58
+ effectiveAllowFrom,
59
+ effectiveGroupAllowFrom,
60
+ groupAllowConfigured: effectiveGroupAllowFrom.length > 0,
61
+ };
62
+ }
63
+
64
+ export async function enforceMatrixDirectMessageAccess(params: {
65
+ dmEnabled: boolean;
66
+ dmPolicy: MatrixDmPolicy;
67
+ accessDecision: "allow" | "block" | "pairing";
68
+ senderId: string;
69
+ senderName: string;
70
+ effectiveAllowFrom: string[];
71
+ upsertPairingRequest: (input: {
72
+ id: string;
73
+ meta?: Record<string, string | undefined>;
74
+ }) => Promise<{
75
+ code: string;
76
+ created: boolean;
77
+ }>;
78
+ sendPairingReply: (text: string) => Promise<void>;
79
+ logVerboseMessage: (message: string) => void;
80
+ }): Promise<boolean> {
81
+ if (!params.dmEnabled) {
82
+ return false;
83
+ }
84
+ if (params.accessDecision === "allow") {
85
+ return true;
86
+ }
87
+ const allowMatch = resolveMatrixAllowListMatch({
88
+ allowList: params.effectiveAllowFrom,
89
+ userId: params.senderId,
90
+ });
91
+ const allowMatchMeta = formatAllowlistMatchMeta(allowMatch);
92
+ if (params.accessDecision === "pairing") {
93
+ await issuePairingChallenge({
94
+ channel: "badgerclaw",
95
+ senderId: params.senderId,
96
+ senderIdLine: `BadgerClaw user id: ${params.senderId}`,
97
+ meta: { name: params.senderName },
98
+ upsertPairingRequest: params.upsertPairingRequest,
99
+ buildReplyText: ({ code }) =>
100
+ [
101
+ "OpenClaw: access not configured.",
102
+ "",
103
+ `Pairing code: ${code}`,
104
+ "",
105
+ "Ask the bot owner to approve with:",
106
+ "openclaw pairing approve badgerclaw <code>",
107
+ ].join("\n"),
108
+ sendPairingReply: params.sendPairingReply,
109
+ onCreated: () => {
110
+ params.logVerboseMessage(
111
+ `badgerclaw pairing request sender=${params.senderId} name=${params.senderName ?? "unknown"} (${allowMatchMeta})`,
112
+ );
113
+ },
114
+ onReplyError: (err) => {
115
+ params.logVerboseMessage(
116
+ `badgerclaw pairing reply failed for ${params.senderId}: ${String(err)}`,
117
+ );
118
+ },
119
+ });
120
+ return false;
121
+ }
122
+ params.logVerboseMessage(
123
+ `badgerclaw: blocked dm sender ${params.senderId} (dmPolicy=${params.dmPolicy}, ${allowMatchMeta})`,
124
+ );
125
+ return false;
126
+ }
@@ -0,0 +1,94 @@
1
+ import {
2
+ compileAllowlist,
3
+ normalizeStringEntries,
4
+ resolveCompiledAllowlistMatch,
5
+ type AllowlistMatch,
6
+ } from "openclaw/plugin-sdk/matrix";
7
+
8
+ function normalizeAllowList(list?: Array<string | number>) {
9
+ return normalizeStringEntries(list);
10
+ }
11
+
12
+ function normalizeMatrixUser(raw?: string | null): string {
13
+ const value = (raw ?? "").trim();
14
+ if (!value) {
15
+ return "";
16
+ }
17
+ if (!value.startsWith("@") || !value.includes(":")) {
18
+ return value.toLowerCase();
19
+ }
20
+ const withoutAt = value.slice(1);
21
+ const splitIndex = withoutAt.indexOf(":");
22
+ if (splitIndex === -1) {
23
+ return value.toLowerCase();
24
+ }
25
+ const localpart = withoutAt.slice(0, splitIndex).toLowerCase();
26
+ const server = withoutAt.slice(splitIndex + 1).toLowerCase();
27
+ if (!server) {
28
+ return value.toLowerCase();
29
+ }
30
+ return `@${localpart}:${server.toLowerCase()}`;
31
+ }
32
+
33
+ export function normalizeMatrixUserId(raw?: string | null): string {
34
+ const trimmed = (raw ?? "").trim();
35
+ if (!trimmed) {
36
+ return "";
37
+ }
38
+ const lowered = trimmed.toLowerCase();
39
+ if (lowered.startsWith("badgerclaw:")) {
40
+ return normalizeMatrixUser(trimmed.slice("badgerclaw:".length));
41
+ }
42
+ if (lowered.startsWith("user:")) {
43
+ return normalizeMatrixUser(trimmed.slice("user:".length));
44
+ }
45
+ return normalizeMatrixUser(trimmed);
46
+ }
47
+
48
+ function normalizeMatrixAllowListEntry(raw: string): string {
49
+ const trimmed = raw.trim();
50
+ if (!trimmed) {
51
+ return "";
52
+ }
53
+ if (trimmed === "*") {
54
+ return trimmed;
55
+ }
56
+ const lowered = trimmed.toLowerCase();
57
+ if (lowered.startsWith("badgerclaw:")) {
58
+ return `badgerclaw:${normalizeMatrixUser(trimmed.slice("badgerclaw:".length))}`;
59
+ }
60
+ if (lowered.startsWith("user:")) {
61
+ return `user:${normalizeMatrixUser(trimmed.slice("user:".length))}`;
62
+ }
63
+ return normalizeMatrixUser(trimmed);
64
+ }
65
+
66
+ export function normalizeMatrixAllowList(list?: Array<string | number>) {
67
+ return normalizeAllowList(list).map((entry) => normalizeMatrixAllowListEntry(entry));
68
+ }
69
+
70
+ export type MatrixAllowListMatch = AllowlistMatch<
71
+ "wildcard" | "id" | "prefixed-id" | "prefixed-user"
72
+ >;
73
+ type MatrixAllowListSource = Exclude<MatrixAllowListMatch["matchSource"], undefined>;
74
+
75
+ export function resolveMatrixAllowListMatch(params: {
76
+ allowList: string[];
77
+ userId?: string;
78
+ }): MatrixAllowListMatch {
79
+ const compiledAllowList = compileAllowlist(params.allowList);
80
+ const userId = normalizeMatrixUser(params.userId);
81
+ const candidates: Array<{ value?: string; source: MatrixAllowListSource }> = [
82
+ { value: userId, source: "id" },
83
+ { value: userId ? `badgerclaw:${userId}` : "", source: "prefixed-id" },
84
+ { value: userId ? `user:${userId}` : "", source: "prefixed-user" },
85
+ ];
86
+ return resolveCompiledAllowlistMatch({
87
+ compiledAllowlist: compiledAllowList,
88
+ candidates,
89
+ });
90
+ }
91
+
92
+ export function resolveMatrixAllowListMatches(params: { allowList: string[]; userId?: string }) {
93
+ return resolveMatrixAllowListMatch(params).allowed;
94
+ }
@@ -0,0 +1,72 @@
1
+ import type { MatrixClient } from "@vector-im/matrix-bot-sdk";
2
+ import type { RuntimeEnv } from "openclaw/plugin-sdk/matrix";
3
+ import { getMatrixRuntime } from "../../runtime.js";
4
+ import type { CoreConfig } from "../../types.js";
5
+ import { loadMatrixSdk } from "../sdk-runtime.js";
6
+
7
+ export function registerMatrixAutoJoin(params: {
8
+ client: MatrixClient;
9
+ cfg: CoreConfig;
10
+ runtime: RuntimeEnv;
11
+ }) {
12
+ const { client, cfg, runtime } = params;
13
+ const core = getMatrixRuntime();
14
+ const logVerbose = (message: string) => {
15
+ if (!core.logging.shouldLogVerbose()) {
16
+ return;
17
+ }
18
+ runtime.log?.(message);
19
+ };
20
+ const autoJoin = cfg.channels?.badgerclaw?.autoJoin ?? "always";
21
+ const autoJoinAllowlist = cfg.channels?.badgerclaw?.autoJoinAllowlist ?? [];
22
+
23
+ if (autoJoin === "off") {
24
+ return;
25
+ }
26
+
27
+ if (autoJoin === "always") {
28
+ // Use the built-in autojoin mixin for "always" mode
29
+ const { AutojoinRoomsMixin } = loadMatrixSdk();
30
+ AutojoinRoomsMixin.setupOnClient(client);
31
+ logVerbose("badgerclaw: auto-join enabled for all invites");
32
+ return;
33
+ }
34
+
35
+ // For "allowlist" mode, handle invites manually
36
+ client.on("room.invite", async (roomId: string, _inviteEvent: unknown) => {
37
+ if (autoJoin !== "allowlist") {
38
+ return;
39
+ }
40
+
41
+ // Get room alias if available
42
+ let alias: string | undefined;
43
+ let altAliases: string[] = [];
44
+ try {
45
+ const aliasState = await client
46
+ .getRoomStateEvent(roomId, "m.room.canonical_alias", "")
47
+ .catch(() => null);
48
+ alias = aliasState?.alias;
49
+ altAliases = Array.isArray(aliasState?.alt_aliases) ? aliasState.alt_aliases : [];
50
+ } catch {
51
+ // Ignore errors
52
+ }
53
+
54
+ const allowed =
55
+ autoJoinAllowlist.includes("*") ||
56
+ autoJoinAllowlist.includes(roomId) ||
57
+ (alias ? autoJoinAllowlist.includes(alias) : false) ||
58
+ altAliases.some((value) => autoJoinAllowlist.includes(value));
59
+
60
+ if (!allowed) {
61
+ logVerbose(`badgerclaw: invite ignored (not in allowlist) room=${roomId}`);
62
+ return;
63
+ }
64
+
65
+ try {
66
+ await client.joinRoom(roomId);
67
+ logVerbose(`badgerclaw: joined room ${roomId}`);
68
+ } catch (err) {
69
+ runtime.error?.(`badgerclaw: failed to join room ${roomId}: ${String(err)}`);
70
+ }
71
+ });
72
+ }