@archipelagolab/lobi 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.
- package/CHANGELOG.md +164 -0
- package/ENDOFFILE +0 -0
- package/EOF +0 -0
- package/LICENSE +21 -0
- package/SPEC-SUPPORT.md +116 -0
- package/YAMLEND +0 -0
- package/api.ts +18 -0
- package/archipelagolab-lobi-1.0.0.tgz +0 -0
- package/auth-presence.ts +56 -0
- package/channel-plugin-api.ts +3 -0
- package/cli-metadata.ts +11 -0
- package/contract-api.ts +17 -0
- package/docs/CHECKLIST.md +83 -0
- package/docs/FORK_SDK_GUIDE.md +279 -0
- package/helper-api.ts +3 -0
- package/index.test.ts +61 -0
- package/index.ts +65 -0
- package/openclaw.plugin.json +23 -0
- package/package.json +52 -0
- package/plugin-entry.handlers.runtime.ts +1 -0
- package/runtime-api.ts +54 -0
- package/runtime-heavy-api.ts +1 -0
- package/scripts/migrate-to-lobi.sh +72 -0
- package/secret-contract-api.ts +5 -0
- package/setup-entry.ts +13 -0
- package/src/account-selection.test.ts +124 -0
- package/src/account-selection.ts +226 -0
- package/src/actions.account-propagation.test.ts +251 -0
- package/src/actions.test.ts +251 -0
- package/src/actions.ts +336 -0
- package/src/approval-auth.test.ts +23 -0
- package/src/approval-auth.ts +25 -0
- package/src/approval-handler.runtime.test.ts +46 -0
- package/src/approval-handler.runtime.ts +400 -0
- package/src/approval-ids.ts +6 -0
- package/src/approval-native.test.ts +329 -0
- package/src/approval-native.ts +336 -0
- package/src/approval-reactions.test.ts +107 -0
- package/src/approval-reactions.ts +158 -0
- package/src/auth-precedence.ts +61 -0
- package/src/channel-account-paths.ts +92 -0
- package/src/channel.account-paths.test.ts +102 -0
- package/src/channel.directory.test.ts +601 -0
- package/src/channel.resolve.test.ts +38 -0
- package/src/channel.runtime.ts +16 -0
- package/src/channel.setup.test.ts +269 -0
- package/src/channel.ts +570 -0
- package/src/cli-metadata.ts +19 -0
- package/src/cli.test.ts +1015 -0
- package/src/cli.ts +1198 -0
- package/src/config-adapter.ts +41 -0
- package/src/config-schema.test.ts +90 -0
- package/src/config-schema.ts +114 -0
- package/src/directory-live.test.ts +200 -0
- package/src/directory-live.ts +238 -0
- package/src/doctor-contract.ts +287 -0
- package/src/doctor.test.ts +440 -0
- package/src/doctor.ts +262 -0
- package/src/env-vars.ts +92 -0
- package/src/exec-approval-resolver.test.ts +68 -0
- package/src/exec-approval-resolver.ts +23 -0
- package/src/exec-approvals.test.ts +483 -0
- package/src/exec-approvals.ts +290 -0
- package/src/group-mentions.ts +41 -0
- package/src/legacy-crypto-inspector-availability.test.ts +81 -0
- package/src/legacy-crypto-inspector-availability.ts +60 -0
- package/src/legacy-crypto.test.ts +234 -0
- package/src/legacy-crypto.ts +549 -0
- package/src/legacy-state.test.ts +86 -0
- package/src/legacy-state.ts +156 -0
- package/src/matrix/account-config.ts +150 -0
- package/src/matrix/accounts.readiness.test.ts +27 -0
- package/src/matrix/accounts.test.ts +757 -0
- package/src/matrix/accounts.ts +194 -0
- package/src/matrix/actions/client.test.ts +215 -0
- package/src/matrix/actions/client.ts +31 -0
- package/src/matrix/actions/devices.test.ts +114 -0
- package/src/matrix/actions/devices.ts +34 -0
- package/src/matrix/actions/limits.test.ts +15 -0
- package/src/matrix/actions/limits.ts +6 -0
- package/src/matrix/actions/messages.test.ts +289 -0
- package/src/matrix/actions/messages.ts +123 -0
- package/src/matrix/actions/pins.test.ts +74 -0
- package/src/matrix/actions/pins.ts +64 -0
- package/src/matrix/actions/polls.test.ts +71 -0
- package/src/matrix/actions/polls.ts +109 -0
- package/src/matrix/actions/profile.test.ts +109 -0
- package/src/matrix/actions/profile.ts +37 -0
- package/src/matrix/actions/reactions.test.ts +135 -0
- package/src/matrix/actions/reactions.ts +59 -0
- package/src/matrix/actions/room.test.ts +79 -0
- package/src/matrix/actions/room.ts +71 -0
- package/src/matrix/actions/summary.test.ts +87 -0
- package/src/matrix/actions/summary.ts +88 -0
- package/src/matrix/actions/types.ts +82 -0
- package/src/matrix/actions/verification.test.ts +105 -0
- package/src/matrix/actions/verification.ts +237 -0
- package/src/matrix/actions.ts +37 -0
- package/src/matrix/active-client.ts +26 -0
- package/src/matrix/async-lock.ts +18 -0
- package/src/matrix/backup-health.ts +115 -0
- package/src/matrix/client/config-runtime-api.ts +14 -0
- package/src/matrix/client/config-secret-input.runtime.ts +1 -0
- package/src/matrix/client/config.ts +982 -0
- package/src/matrix/client/create-client.test.ts +115 -0
- package/src/matrix/client/create-client.ts +101 -0
- package/src/matrix/client/env-auth.ts +6 -0
- package/src/matrix/client/file-sync-store.test.ts +265 -0
- package/src/matrix/client/file-sync-store.ts +289 -0
- package/src/matrix/client/logging.ts +123 -0
- package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
- package/src/matrix/client/private-network-host.ts +56 -0
- package/src/matrix/client/runtime.ts +4 -0
- package/src/matrix/client/shared.test.ts +344 -0
- package/src/matrix/client/shared.ts +306 -0
- package/src/matrix/client/storage.test.ts +634 -0
- package/src/matrix/client/storage.ts +544 -0
- package/src/matrix/client/types.ts +50 -0
- package/src/matrix/client-bootstrap.test.ts +84 -0
- package/src/matrix/client-bootstrap.ts +164 -0
- package/src/matrix/client-resolver.test-helpers.ts +147 -0
- package/src/matrix/client.test.ts +1521 -0
- package/src/matrix/client.ts +23 -0
- package/src/matrix/config-paths.ts +31 -0
- package/src/matrix/config-update.test.ts +237 -0
- package/src/matrix/config-update.ts +291 -0
- package/src/matrix/credentials-read.ts +206 -0
- package/src/matrix/credentials-write.runtime.ts +26 -0
- package/src/matrix/credentials.test.ts +501 -0
- package/src/matrix/credentials.ts +95 -0
- package/src/matrix/deps.test.ts +74 -0
- package/src/matrix/deps.ts +225 -0
- package/src/matrix/device-health.test.ts +45 -0
- package/src/matrix/device-health.ts +31 -0
- package/src/matrix/direct-management.test.ts +350 -0
- package/src/matrix/direct-management.ts +347 -0
- package/src/matrix/direct-room.test.ts +61 -0
- package/src/matrix/direct-room.ts +128 -0
- package/src/matrix/draft-stream.test.ts +406 -0
- package/src/matrix/draft-stream.ts +216 -0
- package/src/matrix/encryption-guidance.ts +27 -0
- package/src/matrix/errors.ts +21 -0
- package/src/matrix/format.test.ts +340 -0
- package/src/matrix/format.ts +428 -0
- package/src/matrix/legacy-crypto-inspector.ts +95 -0
- package/src/matrix/media-errors.ts +20 -0
- package/src/matrix/media-text.ts +169 -0
- package/src/matrix/monitor/access-state.test.ts +45 -0
- package/src/matrix/monitor/access-state.ts +77 -0
- package/src/matrix/monitor/ack-config.test.ts +57 -0
- package/src/matrix/monitor/ack-config.ts +26 -0
- package/src/matrix/monitor/allowlist.test.ts +45 -0
- package/src/matrix/monitor/allowlist.ts +94 -0
- package/src/matrix/monitor/auto-join.test.ts +203 -0
- package/src/matrix/monitor/auto-join.ts +86 -0
- package/src/matrix/monitor/config.test.ts +197 -0
- package/src/matrix/monitor/config.ts +303 -0
- package/src/matrix/monitor/context-summary.ts +43 -0
- package/src/matrix/monitor/direct.test.ts +529 -0
- package/src/matrix/monitor/direct.ts +270 -0
- package/src/matrix/monitor/events.test.ts +1524 -0
- package/src/matrix/monitor/events.ts +213 -0
- package/src/matrix/monitor/handler.body-for-agent.test.ts +396 -0
- package/src/matrix/monitor/handler.group-history.test.ts +648 -0
- package/src/matrix/monitor/handler.media-failure.test.ts +267 -0
- package/src/matrix/monitor/handler.test-helpers.ts +308 -0
- package/src/matrix/monitor/handler.test.ts +2952 -0
- package/src/matrix/monitor/handler.thread-root-media.test.ts +82 -0
- package/src/matrix/monitor/handler.ts +1679 -0
- package/src/matrix/monitor/inbound-dedupe.test.ts +146 -0
- package/src/matrix/monitor/inbound-dedupe.ts +267 -0
- package/src/matrix/monitor/index.test.ts +920 -0
- package/src/matrix/monitor/index.ts +434 -0
- package/src/matrix/monitor/legacy-crypto-restore.test.ts +206 -0
- package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
- package/src/matrix/monitor/location.ts +100 -0
- package/src/matrix/monitor/media.test.ts +159 -0
- package/src/matrix/monitor/media.ts +119 -0
- package/src/matrix/monitor/mentions.test.ts +289 -0
- package/src/matrix/monitor/mentions.ts +177 -0
- package/src/matrix/monitor/reaction-events.test.ts +326 -0
- package/src/matrix/monitor/reaction-events.ts +187 -0
- package/src/matrix/monitor/recent-invite.test.ts +92 -0
- package/src/matrix/monitor/recent-invite.ts +30 -0
- package/src/matrix/monitor/replies.test.ts +265 -0
- package/src/matrix/monitor/replies.ts +136 -0
- package/src/matrix/monitor/reply-context.test.ts +276 -0
- package/src/matrix/monitor/reply-context.ts +92 -0
- package/src/matrix/monitor/room-history.test.ts +258 -0
- package/src/matrix/monitor/room-history.ts +301 -0
- package/src/matrix/monitor/room-info.test.ts +201 -0
- package/src/matrix/monitor/room-info.ts +126 -0
- package/src/matrix/monitor/rooms.test.ts +121 -0
- package/src/matrix/monitor/rooms.ts +52 -0
- package/src/matrix/monitor/route.test.ts +255 -0
- package/src/matrix/monitor/route.ts +178 -0
- package/src/matrix/monitor/runtime-api.ts +31 -0
- package/src/matrix/monitor/startup-verification.test.ts +294 -0
- package/src/matrix/monitor/startup-verification.ts +237 -0
- package/src/matrix/monitor/startup.test.ts +257 -0
- package/src/matrix/monitor/startup.ts +218 -0
- package/src/matrix/monitor/status.ts +111 -0
- package/src/matrix/monitor/sync-lifecycle.test.ts +224 -0
- package/src/matrix/monitor/sync-lifecycle.ts +91 -0
- package/src/matrix/monitor/task-runner.ts +38 -0
- package/src/matrix/monitor/thread-context.test.ts +149 -0
- package/src/matrix/monitor/thread-context.ts +108 -0
- package/src/matrix/monitor/threads.test.ts +68 -0
- package/src/matrix/monitor/threads.ts +85 -0
- package/src/matrix/monitor/types.ts +30 -0
- package/src/matrix/monitor/verification-events.ts +627 -0
- package/src/matrix/monitor/verification-utils.test.ts +47 -0
- package/src/matrix/monitor/verification-utils.ts +46 -0
- package/src/matrix/outbound-media-runtime.ts +1 -0
- package/src/matrix/poll-summary.ts +110 -0
- package/src/matrix/poll-types.test.ts +205 -0
- package/src/matrix/poll-types.ts +433 -0
- package/src/matrix/probe.runtime.ts +4 -0
- package/src/matrix/probe.test.ts +154 -0
- package/src/matrix/probe.ts +96 -0
- package/src/matrix/profile.test.ts +154 -0
- package/src/matrix/profile.ts +184 -0
- package/src/matrix/reaction-common.test.ts +96 -0
- package/src/matrix/reaction-common.ts +147 -0
- package/src/matrix/sdk/crypto-bootstrap.test.ts +505 -0
- package/src/matrix/sdk/crypto-bootstrap.ts +341 -0
- package/src/matrix/sdk/crypto-facade.test.ts +197 -0
- package/src/matrix/sdk/crypto-facade.ts +207 -0
- package/src/matrix/sdk/crypto-node.runtime.test.ts +27 -0
- package/src/matrix/sdk/crypto-node.runtime.ts +9 -0
- package/src/matrix/sdk/crypto-runtime.ts +11 -0
- package/src/matrix/sdk/decrypt-bridge.ts +356 -0
- package/src/matrix/sdk/event-helpers.test.ts +60 -0
- package/src/matrix/sdk/event-helpers.ts +71 -0
- package/src/matrix/sdk/http-client.test.ts +134 -0
- package/src/matrix/sdk/http-client.ts +87 -0
- package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
- package/src/matrix/sdk/idb-persistence.lock-order.test.ts +108 -0
- package/src/matrix/sdk/idb-persistence.test-helpers.ts +88 -0
- package/src/matrix/sdk/idb-persistence.test.ts +149 -0
- package/src/matrix/sdk/idb-persistence.ts +283 -0
- package/src/matrix/sdk/logger.test.ts +25 -0
- package/src/matrix/sdk/logger.ts +108 -0
- package/src/matrix/sdk/read-response-with-limit.ts +19 -0
- package/src/matrix/sdk/recovery-key-store.test.ts +385 -0
- package/src/matrix/sdk/recovery-key-store.ts +430 -0
- package/src/matrix/sdk/transport.test.ts +161 -0
- package/src/matrix/sdk/transport.ts +344 -0
- package/src/matrix/sdk/types.ts +236 -0
- package/src/matrix/sdk/verification-manager.test.ts +509 -0
- package/src/matrix/sdk/verification-manager.ts +694 -0
- package/src/matrix/sdk/verification-status.ts +23 -0
- package/src/matrix/sdk.test.ts +2568 -0
- package/src/matrix/sdk.ts +1789 -0
- package/src/matrix/send/client.test.ts +174 -0
- package/src/matrix/send/client.ts +90 -0
- package/src/matrix/send/formatting.ts +189 -0
- package/src/matrix/send/media.ts +244 -0
- package/src/matrix/send/targets.test.ts +254 -0
- package/src/matrix/send/targets.ts +104 -0
- package/src/matrix/send/types.ts +134 -0
- package/src/matrix/send.test.ts +958 -0
- package/src/matrix/send.ts +609 -0
- package/src/matrix/session-store-metadata.ts +108 -0
- package/src/matrix/startup-abort.ts +44 -0
- package/src/matrix/sync-state.ts +27 -0
- package/src/matrix/target-ids.ts +102 -0
- package/src/matrix/thread-bindings-shared.ts +201 -0
- package/src/matrix/thread-bindings.test.ts +673 -0
- package/src/matrix/thread-bindings.ts +577 -0
- package/src/matrix-migration.runtime.ts +9 -0
- package/src/migration-config.test.ts +228 -0
- package/src/migration-config.ts +243 -0
- package/src/migration-snapshot-backup.ts +117 -0
- package/src/migration-snapshot.test.ts +184 -0
- package/src/migration-snapshot.ts +55 -0
- package/src/onboarding.resolve.test.ts +55 -0
- package/src/onboarding.test-harness.ts +158 -0
- package/src/onboarding.test.ts +665 -0
- package/src/onboarding.ts +773 -0
- package/src/outbound.test.ts +173 -0
- package/src/outbound.ts +78 -0
- package/src/plugin-entry.runtime.js +159 -0
- package/src/plugin-entry.runtime.test.ts +108 -0
- package/src/plugin-entry.runtime.ts +68 -0
- package/src/profile-update.ts +68 -0
- package/src/record-shared.ts +3 -0
- package/src/resolve-targets.test.ts +178 -0
- package/src/resolve-targets.ts +175 -0
- package/src/resolver.ts +21 -0
- package/src/runtime-api.ts +144 -0
- package/src/runtime.ts +7 -0
- package/src/secret-contract.ts +174 -0
- package/src/session-route.test.ts +315 -0
- package/src/session-route.ts +113 -0
- package/src/setup-bootstrap.ts +94 -0
- package/src/setup-config.ts +222 -0
- package/src/setup-contract.ts +89 -0
- package/src/setup-core.test.ts +326 -0
- package/src/setup-core.ts +50 -0
- package/src/setup-surface.ts +4 -0
- package/src/startup-maintenance.test.ts +227 -0
- package/src/startup-maintenance.ts +114 -0
- package/src/storage-paths.ts +92 -0
- package/src/test-helpers.ts +42 -0
- package/src/test-mocks.ts +55 -0
- package/src/test-runtime.ts +72 -0
- package/src/test-support/monitor-route-test-support.ts +8 -0
- package/src/tool-actions.runtime.ts +1 -0
- package/src/tool-actions.test.ts +422 -0
- package/src/tool-actions.ts +498 -0
- package/src/types.ts +230 -0
- package/test-api.ts +2 -0
- package/thread-bindings-runtime.ts +4 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,2568 @@
|
|
|
1
|
+
import "fake-indexeddb/auto";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
7
|
+
|
|
8
|
+
function requestUrl(input: RequestInfo | URL | undefined): string {
|
|
9
|
+
if (!input) {
|
|
10
|
+
return "";
|
|
11
|
+
}
|
|
12
|
+
if (typeof input === "string") {
|
|
13
|
+
return input;
|
|
14
|
+
}
|
|
15
|
+
if (input instanceof URL) {
|
|
16
|
+
return input.toString();
|
|
17
|
+
}
|
|
18
|
+
return input.url;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
class FakeMatrixEvent extends EventEmitter {
|
|
22
|
+
private readonly roomId: string;
|
|
23
|
+
private readonly eventId: string;
|
|
24
|
+
private readonly sender: string;
|
|
25
|
+
private readonly type: string;
|
|
26
|
+
private readonly ts: number;
|
|
27
|
+
private readonly content: Record<string, unknown>;
|
|
28
|
+
private readonly stateKey?: string;
|
|
29
|
+
private readonly unsigned?: {
|
|
30
|
+
age?: number;
|
|
31
|
+
redacted_because?: unknown;
|
|
32
|
+
};
|
|
33
|
+
private readonly decryptionFailure: boolean;
|
|
34
|
+
|
|
35
|
+
constructor(params: {
|
|
36
|
+
roomId: string;
|
|
37
|
+
eventId: string;
|
|
38
|
+
sender: string;
|
|
39
|
+
type: string;
|
|
40
|
+
ts: number;
|
|
41
|
+
content: Record<string, unknown>;
|
|
42
|
+
stateKey?: string;
|
|
43
|
+
unsigned?: {
|
|
44
|
+
age?: number;
|
|
45
|
+
redacted_because?: unknown;
|
|
46
|
+
};
|
|
47
|
+
decryptionFailure?: boolean;
|
|
48
|
+
}) {
|
|
49
|
+
super();
|
|
50
|
+
this.roomId = params.roomId;
|
|
51
|
+
this.eventId = params.eventId;
|
|
52
|
+
this.sender = params.sender;
|
|
53
|
+
this.type = params.type;
|
|
54
|
+
this.ts = params.ts;
|
|
55
|
+
this.content = params.content;
|
|
56
|
+
this.stateKey = params.stateKey;
|
|
57
|
+
this.unsigned = params.unsigned;
|
|
58
|
+
this.decryptionFailure = params.decryptionFailure === true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
getRoomId(): string {
|
|
62
|
+
return this.roomId;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
getId(): string {
|
|
66
|
+
return this.eventId;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
getSender(): string {
|
|
70
|
+
return this.sender;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
getType(): string {
|
|
74
|
+
return this.type;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
getTs(): number {
|
|
78
|
+
return this.ts;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
getContent(): Record<string, unknown> {
|
|
82
|
+
return this.content;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
getUnsigned(): { age?: number; redacted_because?: unknown } {
|
|
86
|
+
return this.unsigned ?? {};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
getStateKey(): string | undefined {
|
|
90
|
+
return this.stateKey;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
isDecryptionFailure(): boolean {
|
|
94
|
+
return this.decryptionFailure;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
type MatrixJsClientStub = {
|
|
99
|
+
emit: (eventName: string | symbol, ...args: unknown[]) => boolean;
|
|
100
|
+
on: (eventName: string | symbol, listener: (...args: unknown[]) => void) => MatrixJsClientStub;
|
|
101
|
+
startClient: ReturnType<typeof vi.fn>;
|
|
102
|
+
stopClient: ReturnType<typeof vi.fn>;
|
|
103
|
+
initRustCrypto: ReturnType<typeof vi.fn>;
|
|
104
|
+
getUserId: ReturnType<typeof vi.fn>;
|
|
105
|
+
getDeviceId: ReturnType<typeof vi.fn>;
|
|
106
|
+
getJoinedRooms: ReturnType<typeof vi.fn>;
|
|
107
|
+
getJoinedRoomMembers: ReturnType<typeof vi.fn>;
|
|
108
|
+
getStateEvent: ReturnType<typeof vi.fn>;
|
|
109
|
+
getAccountData: ReturnType<typeof vi.fn>;
|
|
110
|
+
setAccountData: ReturnType<typeof vi.fn>;
|
|
111
|
+
getRoomIdForAlias: ReturnType<typeof vi.fn>;
|
|
112
|
+
sendMessage: ReturnType<typeof vi.fn>;
|
|
113
|
+
sendEvent: ReturnType<typeof vi.fn>;
|
|
114
|
+
sendStateEvent: ReturnType<typeof vi.fn>;
|
|
115
|
+
redactEvent: ReturnType<typeof vi.fn>;
|
|
116
|
+
getProfileInfo: ReturnType<typeof vi.fn>;
|
|
117
|
+
joinRoom: ReturnType<typeof vi.fn>;
|
|
118
|
+
mxcUrlToHttp: ReturnType<typeof vi.fn>;
|
|
119
|
+
uploadContent: ReturnType<typeof vi.fn>;
|
|
120
|
+
fetchRoomEvent: ReturnType<typeof vi.fn>;
|
|
121
|
+
getEventMapper: ReturnType<typeof vi.fn>;
|
|
122
|
+
sendTyping: ReturnType<typeof vi.fn>;
|
|
123
|
+
getRoom: ReturnType<typeof vi.fn>;
|
|
124
|
+
getRooms: ReturnType<typeof vi.fn>;
|
|
125
|
+
getCrypto: ReturnType<typeof vi.fn>;
|
|
126
|
+
decryptEventIfNeeded: ReturnType<typeof vi.fn>;
|
|
127
|
+
relations: ReturnType<typeof vi.fn>;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
function createMatrixJsClientStub(): MatrixJsClientStub {
|
|
131
|
+
const client = new EventEmitter() as unknown as MatrixJsClientStub;
|
|
132
|
+
client.startClient = vi.fn(async () => {
|
|
133
|
+
queueMicrotask(() => {
|
|
134
|
+
client.emit("sync", "PREPARED", null, undefined);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
client.stopClient = vi.fn();
|
|
138
|
+
client.initRustCrypto = vi.fn(async () => {});
|
|
139
|
+
client.getUserId = vi.fn(() => "@bot:example.org");
|
|
140
|
+
client.getDeviceId = vi.fn(() => "DEVICE123");
|
|
141
|
+
client.getJoinedRooms = vi.fn(async () => ({ joined_rooms: [] }));
|
|
142
|
+
client.getJoinedRoomMembers = vi.fn(async () => ({ joined: {} }));
|
|
143
|
+
client.getStateEvent = vi.fn(async () => ({}));
|
|
144
|
+
client.getAccountData = vi.fn(() => undefined);
|
|
145
|
+
client.setAccountData = vi.fn(async () => {});
|
|
146
|
+
client.getRoomIdForAlias = vi.fn(async () => ({ room_id: "!resolved:example.org" }));
|
|
147
|
+
client.sendMessage = vi.fn(async () => ({ event_id: "$sent" }));
|
|
148
|
+
client.sendEvent = vi.fn(async () => ({ event_id: "$sent-event" }));
|
|
149
|
+
client.sendStateEvent = vi.fn(async () => ({ event_id: "$state" }));
|
|
150
|
+
client.redactEvent = vi.fn(async () => ({ event_id: "$redact" }));
|
|
151
|
+
client.getProfileInfo = vi.fn(async () => ({}));
|
|
152
|
+
client.joinRoom = vi.fn(async () => ({}));
|
|
153
|
+
client.mxcUrlToHttp = vi.fn(() => null);
|
|
154
|
+
client.uploadContent = vi.fn(async () => ({ content_uri: "mxc://example/file" }));
|
|
155
|
+
client.fetchRoomEvent = vi.fn(async () => ({}));
|
|
156
|
+
client.getEventMapper = vi.fn(
|
|
157
|
+
() =>
|
|
158
|
+
(
|
|
159
|
+
raw: Partial<{
|
|
160
|
+
room_id: string;
|
|
161
|
+
event_id: string;
|
|
162
|
+
sender: string;
|
|
163
|
+
type: string;
|
|
164
|
+
origin_server_ts: number;
|
|
165
|
+
content: Record<string, unknown>;
|
|
166
|
+
state_key?: string;
|
|
167
|
+
unsigned?: { age?: number; redacted_because?: unknown };
|
|
168
|
+
}>,
|
|
169
|
+
) =>
|
|
170
|
+
new FakeMatrixEvent({
|
|
171
|
+
roomId: raw.room_id ?? "!mapped:example.org",
|
|
172
|
+
eventId: raw.event_id ?? "$mapped",
|
|
173
|
+
sender: raw.sender ?? "@mapped:example.org",
|
|
174
|
+
type: raw.type ?? "m.room.message",
|
|
175
|
+
ts: raw.origin_server_ts ?? Date.now(),
|
|
176
|
+
content: raw.content ?? {},
|
|
177
|
+
stateKey: raw.state_key,
|
|
178
|
+
unsigned: raw.unsigned,
|
|
179
|
+
}),
|
|
180
|
+
);
|
|
181
|
+
client.sendTyping = vi.fn(async () => {});
|
|
182
|
+
client.getRoom = vi.fn(() => ({ hasEncryptionStateEvent: () => false }));
|
|
183
|
+
client.getRooms = vi.fn(() => []);
|
|
184
|
+
client.getCrypto = vi.fn(() => undefined);
|
|
185
|
+
client.decryptEventIfNeeded = vi.fn(async () => {});
|
|
186
|
+
client.relations = vi.fn(async () => ({
|
|
187
|
+
originalEvent: null,
|
|
188
|
+
events: [],
|
|
189
|
+
nextBatch: null,
|
|
190
|
+
prevBatch: null,
|
|
191
|
+
}));
|
|
192
|
+
return client;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
let matrixJsClient = createMatrixJsClientStub();
|
|
196
|
+
let lastCreateClientOpts: Record<string, unknown> | null = null;
|
|
197
|
+
|
|
198
|
+
vi.mock("@archipelagolab/lobi-js-sdk/lib/matrix.js", async () => {
|
|
199
|
+
const actual = await vi.importActual<typeof import("@archipelagolab/lobi-js-sdk/lib/matrix.js")>(
|
|
200
|
+
"@archipelagolab/lobi-js-sdk/lib/matrix.js",
|
|
201
|
+
);
|
|
202
|
+
return {
|
|
203
|
+
...actual,
|
|
204
|
+
ClientEvent: {
|
|
205
|
+
Event: "event",
|
|
206
|
+
Room: "Room",
|
|
207
|
+
Sync: "sync",
|
|
208
|
+
SyncUnexpectedError: "sync.unexpectedError",
|
|
209
|
+
},
|
|
210
|
+
MatrixEventEvent: { Decrypted: "decrypted" },
|
|
211
|
+
createClient: vi.fn((opts: Record<string, unknown>) => {
|
|
212
|
+
lastCreateClientOpts = opts;
|
|
213
|
+
return matrixJsClient;
|
|
214
|
+
}),
|
|
215
|
+
};
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
const { encodeRecoveryKey } = await import("@archipelagolab/lobi-js-sdk/lib/crypto-api/recovery-key.js");
|
|
219
|
+
const { MatrixClient } = await import("./sdk.js");
|
|
220
|
+
|
|
221
|
+
describe("MatrixClient request hardening", () => {
|
|
222
|
+
beforeEach(() => {
|
|
223
|
+
matrixJsClient = createMatrixJsClientStub();
|
|
224
|
+
lastCreateClientOpts = null;
|
|
225
|
+
vi.useRealTimers();
|
|
226
|
+
vi.unstubAllGlobals();
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
afterEach(() => {
|
|
230
|
+
vi.useRealTimers();
|
|
231
|
+
vi.unstubAllGlobals();
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("blocks absolute endpoints unless explicitly allowed", async () => {
|
|
235
|
+
const fetchMock = vi.fn(async () => {
|
|
236
|
+
return new Response("{}", {
|
|
237
|
+
status: 200,
|
|
238
|
+
headers: { "content-type": "application/json" },
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
|
|
242
|
+
|
|
243
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
244
|
+
await expect(client.doRequest("GET", "https://matrix.example.org/start")).rejects.toThrow(
|
|
245
|
+
"Absolute Matrix endpoint is blocked by default",
|
|
246
|
+
);
|
|
247
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it("injects a guarded fetchFn into matrix-js-sdk", () => {
|
|
251
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
252
|
+
ssrfPolicy: { allowPrivateNetwork: true },
|
|
253
|
+
});
|
|
254
|
+
expect(client).toBeInstanceOf(MatrixClient);
|
|
255
|
+
|
|
256
|
+
expect(lastCreateClientOpts).toMatchObject({
|
|
257
|
+
baseUrl: "https://matrix.example.org",
|
|
258
|
+
accessToken: "token",
|
|
259
|
+
});
|
|
260
|
+
expect(lastCreateClientOpts?.fetchFn).toEqual(expect.any(Function));
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
it("prefers authenticated client media downloads", async () => {
|
|
264
|
+
const payload = Buffer.from([1, 2, 3, 4]);
|
|
265
|
+
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
|
266
|
+
async () => new Response(payload, { status: 200 }),
|
|
267
|
+
);
|
|
268
|
+
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
|
|
269
|
+
|
|
270
|
+
const client = new MatrixClient("http://127.0.0.1:8008", "token", {
|
|
271
|
+
ssrfPolicy: { allowPrivateNetwork: true },
|
|
272
|
+
});
|
|
273
|
+
await expect(client.downloadContent("mxc://example.org/media")).resolves.toEqual(payload);
|
|
274
|
+
|
|
275
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
276
|
+
const firstInput = (fetchMock.mock.calls as Array<[RequestInfo | URL]>)[0]?.[0];
|
|
277
|
+
const firstUrl = requestUrl(firstInput);
|
|
278
|
+
expect(firstUrl).toContain("/_lobi/client/v1/media/download/example.org/media");
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
it("falls back to legacy media downloads for older homeservers", async () => {
|
|
282
|
+
const payload = Buffer.from([5, 6, 7, 8]);
|
|
283
|
+
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
|
284
|
+
const url = requestUrl(input);
|
|
285
|
+
if (url.includes("/_lobi/client/v1/media/download/")) {
|
|
286
|
+
return new Response(
|
|
287
|
+
JSON.stringify({
|
|
288
|
+
errcode: "M_UNRECOGNIZED",
|
|
289
|
+
error: "Unrecognized request",
|
|
290
|
+
}),
|
|
291
|
+
{
|
|
292
|
+
status: 404,
|
|
293
|
+
headers: { "content-type": "application/json" },
|
|
294
|
+
},
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
return new Response(payload, { status: 200 });
|
|
298
|
+
});
|
|
299
|
+
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
|
|
300
|
+
|
|
301
|
+
const client = new MatrixClient("http://127.0.0.1:8008", "token", {
|
|
302
|
+
ssrfPolicy: { allowPrivateNetwork: true },
|
|
303
|
+
});
|
|
304
|
+
await expect(client.downloadContent("mxc://example.org/media")).resolves.toEqual(payload);
|
|
305
|
+
|
|
306
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
307
|
+
const [firstCall, secondCall] = fetchMock.mock.calls as Array<[RequestInfo | URL]>;
|
|
308
|
+
const firstInput = firstCall?.[0];
|
|
309
|
+
const secondInput = secondCall?.[0];
|
|
310
|
+
const firstUrl = requestUrl(firstInput);
|
|
311
|
+
const secondUrl = requestUrl(secondInput);
|
|
312
|
+
expect(firstUrl).toContain("/_lobi/client/v1/media/download/example.org/media");
|
|
313
|
+
expect(secondUrl).toContain("/_lobi/media/v3/download/example.org/media");
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it("decrypts encrypted room events returned by getEvent", async () => {
|
|
317
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
318
|
+
matrixJsClient.fetchRoomEvent = vi.fn(async () => ({
|
|
319
|
+
room_id: "!room:example.org",
|
|
320
|
+
event_id: "$poll",
|
|
321
|
+
sender: "@alice:example.org",
|
|
322
|
+
type: "m.room.encrypted",
|
|
323
|
+
origin_server_ts: 1,
|
|
324
|
+
content: {},
|
|
325
|
+
}));
|
|
326
|
+
matrixJsClient.decryptEventIfNeeded = vi.fn(async (event: FakeMatrixEvent) => {
|
|
327
|
+
event.emit(
|
|
328
|
+
"decrypted",
|
|
329
|
+
new FakeMatrixEvent({
|
|
330
|
+
roomId: "!room:example.org",
|
|
331
|
+
eventId: "$poll",
|
|
332
|
+
sender: "@alice:example.org",
|
|
333
|
+
type: "m.poll.start",
|
|
334
|
+
ts: 1,
|
|
335
|
+
content: {
|
|
336
|
+
"m.poll.start": {
|
|
337
|
+
question: { "m.text": "Lunch?" },
|
|
338
|
+
answers: [{ id: "a1", "m.text": "Pizza" }],
|
|
339
|
+
},
|
|
340
|
+
},
|
|
341
|
+
}),
|
|
342
|
+
);
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
const event = await client.getEvent("!room:example.org", "$poll");
|
|
346
|
+
|
|
347
|
+
expect(matrixJsClient.decryptEventIfNeeded).toHaveBeenCalledTimes(1);
|
|
348
|
+
expect(event).toMatchObject({
|
|
349
|
+
event_id: "$poll",
|
|
350
|
+
type: "m.poll.start",
|
|
351
|
+
sender: "@alice:example.org",
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it("serializes outbound sends per room across message and event sends", async () => {
|
|
356
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
357
|
+
let releaseFirst: (() => void) | undefined;
|
|
358
|
+
const started: string[] = [];
|
|
359
|
+
matrixJsClient.sendMessage = vi.fn(async () => {
|
|
360
|
+
started.push("message");
|
|
361
|
+
await new Promise<void>((resolve) => {
|
|
362
|
+
releaseFirst = resolve;
|
|
363
|
+
});
|
|
364
|
+
return { event_id: "$message" };
|
|
365
|
+
});
|
|
366
|
+
matrixJsClient.sendEvent = vi.fn(async () => {
|
|
367
|
+
started.push("event");
|
|
368
|
+
return { event_id: "$event" };
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
const first = client.sendMessage("!room:example.org", {
|
|
372
|
+
msgtype: "m.text",
|
|
373
|
+
body: "hello",
|
|
374
|
+
});
|
|
375
|
+
const second = client.sendEvent("!room:example.org", "m.reaction", {
|
|
376
|
+
"m.relates_to": { event_id: "$target", key: "👍", rel_type: "m.annotation" },
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
await Promise.resolve();
|
|
380
|
+
await Promise.resolve();
|
|
381
|
+
expect(started).toEqual(["message"]);
|
|
382
|
+
expect(matrixJsClient.sendEvent).not.toHaveBeenCalled();
|
|
383
|
+
|
|
384
|
+
releaseFirst?.();
|
|
385
|
+
|
|
386
|
+
await expect(first).resolves.toBe("$message");
|
|
387
|
+
await expect(second).resolves.toBe("$event");
|
|
388
|
+
expect(started).toEqual(["message", "event"]);
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it("does not serialize sends across different rooms", async () => {
|
|
392
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
393
|
+
let releaseFirst: (() => void) | undefined;
|
|
394
|
+
const started: string[] = [];
|
|
395
|
+
matrixJsClient.sendMessage = vi.fn(async (roomId: string) => {
|
|
396
|
+
started.push(roomId);
|
|
397
|
+
if (roomId === "!room-a:example.org") {
|
|
398
|
+
await new Promise<void>((resolve) => {
|
|
399
|
+
releaseFirst = resolve;
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return { event_id: `$${roomId}` };
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
const first = client.sendMessage("!room-a:example.org", {
|
|
406
|
+
msgtype: "m.text",
|
|
407
|
+
body: "a",
|
|
408
|
+
});
|
|
409
|
+
const second = client.sendMessage("!room-b:example.org", {
|
|
410
|
+
msgtype: "m.text",
|
|
411
|
+
body: "b",
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
await Promise.resolve();
|
|
415
|
+
await Promise.resolve();
|
|
416
|
+
expect(started).toEqual(["!room-a:example.org", "!room-b:example.org"]);
|
|
417
|
+
|
|
418
|
+
releaseFirst?.();
|
|
419
|
+
|
|
420
|
+
await expect(first).resolves.toBe("$!room-a:example.org");
|
|
421
|
+
await expect(second).resolves.toBe("$!room-b:example.org");
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
it("maps relations pages back to raw events", async () => {
|
|
425
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
426
|
+
matrixJsClient.relations = vi.fn(async () => ({
|
|
427
|
+
originalEvent: new FakeMatrixEvent({
|
|
428
|
+
roomId: "!room:example.org",
|
|
429
|
+
eventId: "$poll",
|
|
430
|
+
sender: "@alice:example.org",
|
|
431
|
+
type: "m.poll.start",
|
|
432
|
+
ts: 1,
|
|
433
|
+
content: {
|
|
434
|
+
"m.poll.start": {
|
|
435
|
+
question: { "m.text": "Lunch?" },
|
|
436
|
+
answers: [{ id: "a1", "m.text": "Pizza" }],
|
|
437
|
+
},
|
|
438
|
+
},
|
|
439
|
+
}),
|
|
440
|
+
events: [
|
|
441
|
+
new FakeMatrixEvent({
|
|
442
|
+
roomId: "!room:example.org",
|
|
443
|
+
eventId: "$vote",
|
|
444
|
+
sender: "@bob:example.org",
|
|
445
|
+
type: "m.poll.response",
|
|
446
|
+
ts: 2,
|
|
447
|
+
content: {
|
|
448
|
+
"m.poll.response": { answers: ["a1"] },
|
|
449
|
+
"m.relates_to": { rel_type: "m.reference", event_id: "$poll" },
|
|
450
|
+
},
|
|
451
|
+
}),
|
|
452
|
+
],
|
|
453
|
+
nextBatch: null,
|
|
454
|
+
prevBatch: null,
|
|
455
|
+
}));
|
|
456
|
+
|
|
457
|
+
const page = await client.getRelations("!room:example.org", "$poll", "m.reference");
|
|
458
|
+
|
|
459
|
+
expect(page.originalEvent).toMatchObject({ event_id: "$poll", type: "m.poll.start" });
|
|
460
|
+
expect(page.events).toEqual([
|
|
461
|
+
expect.objectContaining({
|
|
462
|
+
event_id: "$vote",
|
|
463
|
+
type: "m.poll.response",
|
|
464
|
+
sender: "@bob:example.org",
|
|
465
|
+
}),
|
|
466
|
+
]);
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
it("blocks cross-protocol redirects when absolute endpoints are allowed", async () => {
|
|
470
|
+
const fetchMock = vi.fn(async () => {
|
|
471
|
+
return new Response("", {
|
|
472
|
+
status: 302,
|
|
473
|
+
headers: {
|
|
474
|
+
location: "https://127.0.0.2:8008/next",
|
|
475
|
+
},
|
|
476
|
+
});
|
|
477
|
+
});
|
|
478
|
+
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
|
|
479
|
+
|
|
480
|
+
const client = new MatrixClient("http://127.0.0.1:8008", "token", {
|
|
481
|
+
ssrfPolicy: { allowPrivateNetwork: true },
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
await expect(
|
|
485
|
+
client.doRequest("GET", "http://127.0.0.1:8008/start", undefined, undefined, {
|
|
486
|
+
allowAbsoluteEndpoint: true,
|
|
487
|
+
}),
|
|
488
|
+
).rejects.toThrow("Blocked cross-protocol redirect");
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
it("strips authorization when redirect crosses origin", async () => {
|
|
492
|
+
const calls: Array<{ url: string; headers: Headers }> = [];
|
|
493
|
+
const fetchMock = vi.fn(async (url: URL | string, init?: RequestInit) => {
|
|
494
|
+
calls.push({
|
|
495
|
+
url: String(url),
|
|
496
|
+
headers: new Headers(init?.headers),
|
|
497
|
+
});
|
|
498
|
+
if (calls.length === 1) {
|
|
499
|
+
return new Response("", {
|
|
500
|
+
status: 302,
|
|
501
|
+
headers: { location: "http://127.0.0.2:8008/next" },
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
return new Response("{}", {
|
|
505
|
+
status: 200,
|
|
506
|
+
headers: { "content-type": "application/json" },
|
|
507
|
+
});
|
|
508
|
+
});
|
|
509
|
+
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
|
|
510
|
+
|
|
511
|
+
const client = new MatrixClient("http://127.0.0.1:8008", "token", {
|
|
512
|
+
ssrfPolicy: { allowPrivateNetwork: true },
|
|
513
|
+
});
|
|
514
|
+
await client.doRequest("GET", "http://127.0.0.1:8008/start", undefined, undefined, {
|
|
515
|
+
allowAbsoluteEndpoint: true,
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
expect(calls).toHaveLength(2);
|
|
519
|
+
expect(calls[0]?.url).toBe("http://127.0.0.1:8008/start");
|
|
520
|
+
expect(calls[0]?.headers.get("authorization")).toBe("Bearer token");
|
|
521
|
+
expect(calls[1]?.url).toBe("http://127.0.0.2:8008/next");
|
|
522
|
+
expect(calls[1]?.headers.get("authorization")).toBeNull();
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
it("aborts requests after timeout", async () => {
|
|
526
|
+
vi.useFakeTimers();
|
|
527
|
+
const fetchMock = vi.fn((_: URL | string, init?: RequestInit) => {
|
|
528
|
+
return new Promise<Response>((_, reject) => {
|
|
529
|
+
init?.signal?.addEventListener("abort", () => {
|
|
530
|
+
reject(new Error("aborted"));
|
|
531
|
+
});
|
|
532
|
+
});
|
|
533
|
+
});
|
|
534
|
+
vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
|
|
535
|
+
|
|
536
|
+
const client = new MatrixClient("http://127.0.0.1:8008", "token", {
|
|
537
|
+
localTimeoutMs: 25,
|
|
538
|
+
ssrfPolicy: { allowPrivateNetwork: true },
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
const pending = client.doRequest("GET", "/_lobi/client/v3/account/whoami");
|
|
542
|
+
const assertion = expect(pending).rejects.toThrow("aborted");
|
|
543
|
+
await vi.advanceTimersByTimeAsync(30);
|
|
544
|
+
|
|
545
|
+
await assertion;
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
it("wires the sync store into the SDK and flushes it on shutdown", async () => {
|
|
549
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-matrix-sdk-store-"));
|
|
550
|
+
const storagePath = path.join(tempDir, "bot-storage.json");
|
|
551
|
+
|
|
552
|
+
try {
|
|
553
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
554
|
+
storagePath,
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
const store = lastCreateClientOpts?.store as { flush: () => Promise<void> } | undefined;
|
|
558
|
+
expect(store).toBeTruthy();
|
|
559
|
+
const flushSpy = vi.spyOn(store!, "flush").mockResolvedValue();
|
|
560
|
+
|
|
561
|
+
await client.stopAndPersist();
|
|
562
|
+
|
|
563
|
+
expect(flushSpy).toHaveBeenCalledTimes(1);
|
|
564
|
+
expect(matrixJsClient.stopClient).toHaveBeenCalledTimes(1);
|
|
565
|
+
} finally {
|
|
566
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
567
|
+
}
|
|
568
|
+
});
|
|
569
|
+
});
|
|
570
|
+
|
|
571
|
+
describe("MatrixClient event bridge", () => {
|
|
572
|
+
beforeEach(() => {
|
|
573
|
+
matrixJsClient = createMatrixJsClientStub();
|
|
574
|
+
lastCreateClientOpts = null;
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
afterEach(() => {
|
|
578
|
+
vi.useRealTimers();
|
|
579
|
+
vi.restoreAllMocks();
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
it("emits room.message only after encrypted events decrypt", async () => {
|
|
583
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
584
|
+
const messageEvents: Array<{ roomId: string; type: string }> = [];
|
|
585
|
+
|
|
586
|
+
client.on("room.message", (roomId, event) => {
|
|
587
|
+
messageEvents.push({ roomId, type: event.type });
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
await client.start();
|
|
591
|
+
|
|
592
|
+
const encrypted = new FakeMatrixEvent({
|
|
593
|
+
roomId: "!room:example.org",
|
|
594
|
+
eventId: "$event",
|
|
595
|
+
sender: "@alice:example.org",
|
|
596
|
+
type: "m.room.encrypted",
|
|
597
|
+
ts: Date.now(),
|
|
598
|
+
content: {},
|
|
599
|
+
});
|
|
600
|
+
const decrypted = new FakeMatrixEvent({
|
|
601
|
+
roomId: "!room:example.org",
|
|
602
|
+
eventId: "$event",
|
|
603
|
+
sender: "@alice:example.org",
|
|
604
|
+
type: "m.room.message",
|
|
605
|
+
ts: Date.now(),
|
|
606
|
+
content: {
|
|
607
|
+
msgtype: "m.text",
|
|
608
|
+
body: "hello",
|
|
609
|
+
},
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
matrixJsClient.emit("event", encrypted);
|
|
613
|
+
expect(messageEvents).toHaveLength(0);
|
|
614
|
+
|
|
615
|
+
encrypted.emit("decrypted", decrypted);
|
|
616
|
+
// Simulate a second normal event emission from the SDK after decryption.
|
|
617
|
+
matrixJsClient.emit("event", decrypted);
|
|
618
|
+
expect(messageEvents).toEqual([
|
|
619
|
+
{
|
|
620
|
+
roomId: "!room:example.org",
|
|
621
|
+
type: "m.room.message",
|
|
622
|
+
},
|
|
623
|
+
]);
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
it("emits room.failed_decryption when decrypting fails", async () => {
|
|
627
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
628
|
+
const failed: string[] = [];
|
|
629
|
+
const delivered: string[] = [];
|
|
630
|
+
|
|
631
|
+
client.on("room.failed_decryption", (_roomId, _event, error) => {
|
|
632
|
+
failed.push(error.message);
|
|
633
|
+
});
|
|
634
|
+
client.on("room.message", (_roomId, event) => {
|
|
635
|
+
delivered.push(event.type);
|
|
636
|
+
});
|
|
637
|
+
|
|
638
|
+
await client.start();
|
|
639
|
+
|
|
640
|
+
const encrypted = new FakeMatrixEvent({
|
|
641
|
+
roomId: "!room:example.org",
|
|
642
|
+
eventId: "$event",
|
|
643
|
+
sender: "@alice:example.org",
|
|
644
|
+
type: "m.room.encrypted",
|
|
645
|
+
ts: Date.now(),
|
|
646
|
+
content: {},
|
|
647
|
+
});
|
|
648
|
+
const decrypted = new FakeMatrixEvent({
|
|
649
|
+
roomId: "!room:example.org",
|
|
650
|
+
eventId: "$event",
|
|
651
|
+
sender: "@alice:example.org",
|
|
652
|
+
type: "m.room.message",
|
|
653
|
+
ts: Date.now(),
|
|
654
|
+
content: {
|
|
655
|
+
msgtype: "m.text",
|
|
656
|
+
body: "hello",
|
|
657
|
+
},
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
matrixJsClient.emit("event", encrypted);
|
|
661
|
+
encrypted.emit("decrypted", decrypted, new Error("decrypt failed"));
|
|
662
|
+
|
|
663
|
+
expect(failed).toEqual(["decrypt failed"]);
|
|
664
|
+
expect(delivered).toHaveLength(0);
|
|
665
|
+
});
|
|
666
|
+
|
|
667
|
+
it("retries failed decryption and emits room.message after late key availability", async () => {
|
|
668
|
+
vi.useFakeTimers();
|
|
669
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
670
|
+
const failed: string[] = [];
|
|
671
|
+
const delivered: string[] = [];
|
|
672
|
+
|
|
673
|
+
client.on("room.failed_decryption", (_roomId, _event, error) => {
|
|
674
|
+
failed.push(error.message);
|
|
675
|
+
});
|
|
676
|
+
client.on("room.message", (_roomId, event) => {
|
|
677
|
+
delivered.push(event.type);
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
const encrypted = new FakeMatrixEvent({
|
|
681
|
+
roomId: "!room:example.org",
|
|
682
|
+
eventId: "$event",
|
|
683
|
+
sender: "@alice:example.org",
|
|
684
|
+
type: "m.room.encrypted",
|
|
685
|
+
ts: Date.now(),
|
|
686
|
+
content: {},
|
|
687
|
+
decryptionFailure: true,
|
|
688
|
+
});
|
|
689
|
+
const decrypted = new FakeMatrixEvent({
|
|
690
|
+
roomId: "!room:example.org",
|
|
691
|
+
eventId: "$event",
|
|
692
|
+
sender: "@alice:example.org",
|
|
693
|
+
type: "m.room.message",
|
|
694
|
+
ts: Date.now(),
|
|
695
|
+
content: {
|
|
696
|
+
msgtype: "m.text",
|
|
697
|
+
body: "hello",
|
|
698
|
+
},
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
matrixJsClient.decryptEventIfNeeded = vi.fn(async () => {
|
|
702
|
+
encrypted.emit("decrypted", decrypted);
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
await client.start();
|
|
706
|
+
matrixJsClient.emit("event", encrypted);
|
|
707
|
+
encrypted.emit("decrypted", encrypted, new Error("missing room key"));
|
|
708
|
+
|
|
709
|
+
expect(failed).toEqual(["missing room key"]);
|
|
710
|
+
expect(delivered).toHaveLength(0);
|
|
711
|
+
|
|
712
|
+
await vi.advanceTimersByTimeAsync(1_600);
|
|
713
|
+
|
|
714
|
+
expect(matrixJsClient.decryptEventIfNeeded).toHaveBeenCalledTimes(1);
|
|
715
|
+
expect(failed).toEqual(["missing room key"]);
|
|
716
|
+
expect(delivered).toEqual(["m.room.message"]);
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
it("can drain pending decrypt retries after sync stops", async () => {
|
|
720
|
+
vi.useFakeTimers();
|
|
721
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
722
|
+
const delivered: string[] = [];
|
|
723
|
+
|
|
724
|
+
client.on("room.message", (_roomId, event) => {
|
|
725
|
+
delivered.push(event.type);
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
const encrypted = new FakeMatrixEvent({
|
|
729
|
+
roomId: "!room:example.org",
|
|
730
|
+
eventId: "$event",
|
|
731
|
+
sender: "@alice:example.org",
|
|
732
|
+
type: "m.room.encrypted",
|
|
733
|
+
ts: Date.now(),
|
|
734
|
+
content: {},
|
|
735
|
+
decryptionFailure: true,
|
|
736
|
+
});
|
|
737
|
+
const decrypted = new FakeMatrixEvent({
|
|
738
|
+
roomId: "!room:example.org",
|
|
739
|
+
eventId: "$event",
|
|
740
|
+
sender: "@alice:example.org",
|
|
741
|
+
type: "m.room.message",
|
|
742
|
+
ts: Date.now(),
|
|
743
|
+
content: {
|
|
744
|
+
msgtype: "m.text",
|
|
745
|
+
body: "hello",
|
|
746
|
+
},
|
|
747
|
+
});
|
|
748
|
+
|
|
749
|
+
matrixJsClient.decryptEventIfNeeded = vi.fn(async () => {
|
|
750
|
+
encrypted.emit("decrypted", decrypted);
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
await client.start();
|
|
754
|
+
matrixJsClient.emit("event", encrypted);
|
|
755
|
+
encrypted.emit("decrypted", encrypted, new Error("missing room key"));
|
|
756
|
+
|
|
757
|
+
client.stopSyncWithoutPersist();
|
|
758
|
+
await client.drainPendingDecryptions("test shutdown");
|
|
759
|
+
|
|
760
|
+
expect(matrixJsClient.stopClient).toHaveBeenCalledTimes(1);
|
|
761
|
+
expect(matrixJsClient.decryptEventIfNeeded).toHaveBeenCalledTimes(1);
|
|
762
|
+
expect(delivered).toEqual(["m.room.message"]);
|
|
763
|
+
});
|
|
764
|
+
|
|
765
|
+
it("retries failed decryptions immediately on crypto key update signals", async () => {
|
|
766
|
+
vi.useFakeTimers();
|
|
767
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
768
|
+
encryption: true,
|
|
769
|
+
});
|
|
770
|
+
const failed: string[] = [];
|
|
771
|
+
const delivered: string[] = [];
|
|
772
|
+
const cryptoListeners = new Map<string, (...args: unknown[]) => void>();
|
|
773
|
+
|
|
774
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
775
|
+
on: vi.fn((eventName: string, listener: (...args: unknown[]) => void) => {
|
|
776
|
+
cryptoListeners.set(eventName, listener);
|
|
777
|
+
}),
|
|
778
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
779
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
780
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
781
|
+
}));
|
|
782
|
+
|
|
783
|
+
client.on("room.failed_decryption", (_roomId, _event, error) => {
|
|
784
|
+
failed.push(error.message);
|
|
785
|
+
});
|
|
786
|
+
client.on("room.message", (_roomId, event) => {
|
|
787
|
+
delivered.push(event.type);
|
|
788
|
+
});
|
|
789
|
+
|
|
790
|
+
const encrypted = new FakeMatrixEvent({
|
|
791
|
+
roomId: "!room:example.org",
|
|
792
|
+
eventId: "$event",
|
|
793
|
+
sender: "@alice:example.org",
|
|
794
|
+
type: "m.room.encrypted",
|
|
795
|
+
ts: Date.now(),
|
|
796
|
+
content: {},
|
|
797
|
+
decryptionFailure: true,
|
|
798
|
+
});
|
|
799
|
+
const decrypted = new FakeMatrixEvent({
|
|
800
|
+
roomId: "!room:example.org",
|
|
801
|
+
eventId: "$event",
|
|
802
|
+
sender: "@alice:example.org",
|
|
803
|
+
type: "m.room.message",
|
|
804
|
+
ts: Date.now(),
|
|
805
|
+
content: {
|
|
806
|
+
msgtype: "m.text",
|
|
807
|
+
body: "hello",
|
|
808
|
+
},
|
|
809
|
+
});
|
|
810
|
+
matrixJsClient.decryptEventIfNeeded = vi.fn(async () => {
|
|
811
|
+
encrypted.emit("decrypted", decrypted);
|
|
812
|
+
});
|
|
813
|
+
|
|
814
|
+
await client.start();
|
|
815
|
+
matrixJsClient.emit("event", encrypted);
|
|
816
|
+
encrypted.emit("decrypted", encrypted, new Error("missing room key"));
|
|
817
|
+
|
|
818
|
+
expect(failed).toEqual(["missing room key"]);
|
|
819
|
+
expect(delivered).toHaveLength(0);
|
|
820
|
+
|
|
821
|
+
const trigger = cryptoListeners.get("crypto.keyBackupDecryptionKeyCached");
|
|
822
|
+
expect(trigger).toBeTypeOf("function");
|
|
823
|
+
trigger?.();
|
|
824
|
+
await Promise.resolve();
|
|
825
|
+
|
|
826
|
+
expect(matrixJsClient.decryptEventIfNeeded).toHaveBeenCalledTimes(1);
|
|
827
|
+
expect(delivered).toEqual(["m.room.message"]);
|
|
828
|
+
});
|
|
829
|
+
|
|
830
|
+
it("stops decryption retries after hitting retry cap", async () => {
|
|
831
|
+
vi.useFakeTimers();
|
|
832
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
833
|
+
const failed: string[] = [];
|
|
834
|
+
|
|
835
|
+
client.on("room.failed_decryption", (_roomId, _event, error) => {
|
|
836
|
+
failed.push(error.message);
|
|
837
|
+
});
|
|
838
|
+
|
|
839
|
+
const encrypted = new FakeMatrixEvent({
|
|
840
|
+
roomId: "!room:example.org",
|
|
841
|
+
eventId: "$event",
|
|
842
|
+
sender: "@alice:example.org",
|
|
843
|
+
type: "m.room.encrypted",
|
|
844
|
+
ts: Date.now(),
|
|
845
|
+
content: {},
|
|
846
|
+
decryptionFailure: true,
|
|
847
|
+
});
|
|
848
|
+
|
|
849
|
+
matrixJsClient.decryptEventIfNeeded = vi.fn(async () => {
|
|
850
|
+
throw new Error("still missing key");
|
|
851
|
+
});
|
|
852
|
+
|
|
853
|
+
await client.start();
|
|
854
|
+
matrixJsClient.emit("event", encrypted);
|
|
855
|
+
encrypted.emit("decrypted", encrypted, new Error("missing room key"));
|
|
856
|
+
|
|
857
|
+
expect(failed).toEqual(["missing room key"]);
|
|
858
|
+
|
|
859
|
+
await vi.advanceTimersByTimeAsync(200_000);
|
|
860
|
+
expect(matrixJsClient.decryptEventIfNeeded).toHaveBeenCalledTimes(8);
|
|
861
|
+
|
|
862
|
+
await vi.advanceTimersByTimeAsync(200_000);
|
|
863
|
+
expect(matrixJsClient.decryptEventIfNeeded).toHaveBeenCalledTimes(8);
|
|
864
|
+
});
|
|
865
|
+
|
|
866
|
+
it("does not start duplicate retries when crypto signals fire while retry is in-flight", async () => {
|
|
867
|
+
vi.useFakeTimers();
|
|
868
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
869
|
+
encryption: true,
|
|
870
|
+
});
|
|
871
|
+
const delivered: string[] = [];
|
|
872
|
+
const cryptoListeners = new Map<string, (...args: unknown[]) => void>();
|
|
873
|
+
|
|
874
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
875
|
+
on: vi.fn((eventName: string, listener: (...args: unknown[]) => void) => {
|
|
876
|
+
cryptoListeners.set(eventName, listener);
|
|
877
|
+
}),
|
|
878
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
879
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
880
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
881
|
+
}));
|
|
882
|
+
|
|
883
|
+
client.on("room.message", (_roomId, event) => {
|
|
884
|
+
delivered.push(event.type);
|
|
885
|
+
});
|
|
886
|
+
|
|
887
|
+
const encrypted = new FakeMatrixEvent({
|
|
888
|
+
roomId: "!room:example.org",
|
|
889
|
+
eventId: "$event",
|
|
890
|
+
sender: "@alice:example.org",
|
|
891
|
+
type: "m.room.encrypted",
|
|
892
|
+
ts: Date.now(),
|
|
893
|
+
content: {},
|
|
894
|
+
decryptionFailure: true,
|
|
895
|
+
});
|
|
896
|
+
const decrypted = new FakeMatrixEvent({
|
|
897
|
+
roomId: "!room:example.org",
|
|
898
|
+
eventId: "$event",
|
|
899
|
+
sender: "@alice:example.org",
|
|
900
|
+
type: "m.room.message",
|
|
901
|
+
ts: Date.now(),
|
|
902
|
+
content: {
|
|
903
|
+
msgtype: "m.text",
|
|
904
|
+
body: "hello",
|
|
905
|
+
},
|
|
906
|
+
});
|
|
907
|
+
|
|
908
|
+
const releaseRetryRef: { current?: () => void } = {};
|
|
909
|
+
matrixJsClient.decryptEventIfNeeded = vi.fn(
|
|
910
|
+
async () =>
|
|
911
|
+
await new Promise<void>((resolve) => {
|
|
912
|
+
releaseRetryRef.current = () => {
|
|
913
|
+
encrypted.emit("decrypted", decrypted);
|
|
914
|
+
resolve();
|
|
915
|
+
};
|
|
916
|
+
}),
|
|
917
|
+
);
|
|
918
|
+
|
|
919
|
+
await client.start();
|
|
920
|
+
matrixJsClient.emit("event", encrypted);
|
|
921
|
+
encrypted.emit("decrypted", encrypted, new Error("missing room key"));
|
|
922
|
+
|
|
923
|
+
const trigger = cryptoListeners.get("crypto.keyBackupDecryptionKeyCached");
|
|
924
|
+
expect(trigger).toBeTypeOf("function");
|
|
925
|
+
trigger?.();
|
|
926
|
+
trigger?.();
|
|
927
|
+
await Promise.resolve();
|
|
928
|
+
|
|
929
|
+
expect(matrixJsClient.decryptEventIfNeeded).toHaveBeenCalledTimes(1);
|
|
930
|
+
releaseRetryRef.current?.();
|
|
931
|
+
await Promise.resolve();
|
|
932
|
+
expect(delivered).toEqual(["m.room.message"]);
|
|
933
|
+
});
|
|
934
|
+
|
|
935
|
+
it("emits room.invite when a membership invite targets the current user", async () => {
|
|
936
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
937
|
+
const invites: string[] = [];
|
|
938
|
+
|
|
939
|
+
client.on("room.invite", (roomId) => {
|
|
940
|
+
invites.push(roomId);
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
await client.start();
|
|
944
|
+
|
|
945
|
+
const inviteMembership = new FakeMatrixEvent({
|
|
946
|
+
roomId: "!room:example.org",
|
|
947
|
+
eventId: "$invite",
|
|
948
|
+
sender: "@alice:example.org",
|
|
949
|
+
type: "m.room.member",
|
|
950
|
+
ts: Date.now(),
|
|
951
|
+
stateKey: "@bot:example.org",
|
|
952
|
+
content: {
|
|
953
|
+
membership: "invite",
|
|
954
|
+
},
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
matrixJsClient.emit("event", inviteMembership);
|
|
958
|
+
|
|
959
|
+
expect(invites).toEqual(["!room:example.org"]);
|
|
960
|
+
});
|
|
961
|
+
|
|
962
|
+
it("emits room.invite when SDK emits Room event with invite membership", async () => {
|
|
963
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
964
|
+
const invites: string[] = [];
|
|
965
|
+
client.on("room.invite", (roomId) => {
|
|
966
|
+
invites.push(roomId);
|
|
967
|
+
});
|
|
968
|
+
|
|
969
|
+
await client.start();
|
|
970
|
+
|
|
971
|
+
matrixJsClient.emit("Room", {
|
|
972
|
+
roomId: "!invite:example.org",
|
|
973
|
+
getMyMembership: () => "invite",
|
|
974
|
+
});
|
|
975
|
+
|
|
976
|
+
expect(invites).toEqual(["!invite:example.org"]);
|
|
977
|
+
});
|
|
978
|
+
|
|
979
|
+
it("waits for a ready sync state before resolving startup", async () => {
|
|
980
|
+
let releaseSyncReady: (() => void) | undefined;
|
|
981
|
+
matrixJsClient.startClient = vi.fn(async () => {
|
|
982
|
+
await new Promise<void>((resolve) => {
|
|
983
|
+
releaseSyncReady = () => {
|
|
984
|
+
matrixJsClient.emit("sync", "PREPARED", null, undefined);
|
|
985
|
+
resolve();
|
|
986
|
+
};
|
|
987
|
+
});
|
|
988
|
+
});
|
|
989
|
+
|
|
990
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
991
|
+
let resolved = false;
|
|
992
|
+
const startPromise = client.start().then(() => {
|
|
993
|
+
resolved = true;
|
|
994
|
+
});
|
|
995
|
+
|
|
996
|
+
await vi.waitFor(() => {
|
|
997
|
+
expect(releaseSyncReady).toEqual(expect.any(Function));
|
|
998
|
+
});
|
|
999
|
+
expect(resolved).toBe(false);
|
|
1000
|
+
|
|
1001
|
+
releaseSyncReady?.();
|
|
1002
|
+
await startPromise;
|
|
1003
|
+
|
|
1004
|
+
expect(resolved).toBe(true);
|
|
1005
|
+
});
|
|
1006
|
+
|
|
1007
|
+
it("rejects startup when sync reports an unexpected error before ready", async () => {
|
|
1008
|
+
matrixJsClient.startClient = vi.fn(async () => {
|
|
1009
|
+
const timer = setTimeout(() => {
|
|
1010
|
+
matrixJsClient.emit("sync.unexpectedError", new Error("sync exploded"));
|
|
1011
|
+
}, 0);
|
|
1012
|
+
timer.unref?.();
|
|
1013
|
+
});
|
|
1014
|
+
|
|
1015
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1016
|
+
|
|
1017
|
+
await expect(client.start()).rejects.toThrow("sync exploded");
|
|
1018
|
+
});
|
|
1019
|
+
|
|
1020
|
+
it("allows transient startup ERROR to recover into PREPARED", async () => {
|
|
1021
|
+
matrixJsClient.startClient = vi.fn(async () => {
|
|
1022
|
+
queueMicrotask(() => {
|
|
1023
|
+
matrixJsClient.emit("sync", "ERROR", null, new Error("temporary outage"));
|
|
1024
|
+
queueMicrotask(() => {
|
|
1025
|
+
matrixJsClient.emit("sync", "PREPARED", "ERROR", undefined);
|
|
1026
|
+
});
|
|
1027
|
+
});
|
|
1028
|
+
});
|
|
1029
|
+
|
|
1030
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1031
|
+
|
|
1032
|
+
await expect(client.start()).resolves.toBeUndefined();
|
|
1033
|
+
});
|
|
1034
|
+
|
|
1035
|
+
it("aborts startup when the readiness wait is canceled", async () => {
|
|
1036
|
+
matrixJsClient.startClient = vi.fn(async () => {});
|
|
1037
|
+
|
|
1038
|
+
const abortController = new AbortController();
|
|
1039
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1040
|
+
const startPromise = client.start({ abortSignal: abortController.signal });
|
|
1041
|
+
|
|
1042
|
+
abortController.abort();
|
|
1043
|
+
|
|
1044
|
+
await expect(startPromise).rejects.toMatchObject({
|
|
1045
|
+
message: "Matrix startup aborted",
|
|
1046
|
+
name: "AbortError",
|
|
1047
|
+
});
|
|
1048
|
+
});
|
|
1049
|
+
|
|
1050
|
+
it("aborts before post-ready startup work when shutdown races ready sync", async () => {
|
|
1051
|
+
matrixJsClient.startClient = vi.fn(async () => {
|
|
1052
|
+
queueMicrotask(() => {
|
|
1053
|
+
matrixJsClient.emit("sync", "PREPARED", null, undefined);
|
|
1054
|
+
});
|
|
1055
|
+
});
|
|
1056
|
+
|
|
1057
|
+
const abortController = new AbortController();
|
|
1058
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1059
|
+
const bootstrapCryptoSpy = vi.spyOn(
|
|
1060
|
+
client as unknown as { bootstrapCryptoIfNeeded: () => Promise<void> },
|
|
1061
|
+
"bootstrapCryptoIfNeeded",
|
|
1062
|
+
);
|
|
1063
|
+
bootstrapCryptoSpy.mockImplementation(async () => {});
|
|
1064
|
+
|
|
1065
|
+
client.on("sync.state", (state) => {
|
|
1066
|
+
if (state === "PREPARED") {
|
|
1067
|
+
abortController.abort();
|
|
1068
|
+
}
|
|
1069
|
+
});
|
|
1070
|
+
|
|
1071
|
+
await expect(client.start({ abortSignal: abortController.signal })).rejects.toMatchObject({
|
|
1072
|
+
message: "Matrix startup aborted",
|
|
1073
|
+
name: "AbortError",
|
|
1074
|
+
});
|
|
1075
|
+
expect(bootstrapCryptoSpy).not.toHaveBeenCalled();
|
|
1076
|
+
});
|
|
1077
|
+
|
|
1078
|
+
it("times out startup when no ready sync state arrives", async () => {
|
|
1079
|
+
vi.useFakeTimers();
|
|
1080
|
+
matrixJsClient.startClient = vi.fn(async () => {});
|
|
1081
|
+
|
|
1082
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1083
|
+
const startPromise = client.start();
|
|
1084
|
+
const startExpectation = expect(startPromise).rejects.toThrow(
|
|
1085
|
+
"Matrix client did not reach a ready sync state within 30000ms",
|
|
1086
|
+
);
|
|
1087
|
+
|
|
1088
|
+
await vi.advanceTimersByTimeAsync(30_000);
|
|
1089
|
+
|
|
1090
|
+
await startExpectation;
|
|
1091
|
+
});
|
|
1092
|
+
|
|
1093
|
+
it("clears stale sync state before a restarted sync session waits for fresh readiness", async () => {
|
|
1094
|
+
matrixJsClient.startClient = vi
|
|
1095
|
+
.fn(async () => {
|
|
1096
|
+
queueMicrotask(() => {
|
|
1097
|
+
matrixJsClient.emit("sync", "PREPARED", null, undefined);
|
|
1098
|
+
});
|
|
1099
|
+
})
|
|
1100
|
+
.mockImplementationOnce(async () => {
|
|
1101
|
+
queueMicrotask(() => {
|
|
1102
|
+
matrixJsClient.emit("sync", "PREPARED", null, undefined);
|
|
1103
|
+
});
|
|
1104
|
+
})
|
|
1105
|
+
.mockImplementationOnce(async () => {});
|
|
1106
|
+
|
|
1107
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1108
|
+
|
|
1109
|
+
await client.start();
|
|
1110
|
+
client.stopSyncWithoutPersist();
|
|
1111
|
+
|
|
1112
|
+
vi.useFakeTimers();
|
|
1113
|
+
const restartPromise = client.start();
|
|
1114
|
+
const restartExpectation = expect(restartPromise).rejects.toThrow(
|
|
1115
|
+
"Matrix client did not reach a ready sync state within 30000ms",
|
|
1116
|
+
);
|
|
1117
|
+
|
|
1118
|
+
await vi.advanceTimersByTimeAsync(30_000);
|
|
1119
|
+
|
|
1120
|
+
await restartExpectation;
|
|
1121
|
+
});
|
|
1122
|
+
|
|
1123
|
+
it("replays outstanding invite rooms at startup", async () => {
|
|
1124
|
+
matrixJsClient.getRooms = vi.fn(() => [
|
|
1125
|
+
{
|
|
1126
|
+
roomId: "!pending:example.org",
|
|
1127
|
+
getMyMembership: () => "invite",
|
|
1128
|
+
},
|
|
1129
|
+
{
|
|
1130
|
+
roomId: "!joined:example.org",
|
|
1131
|
+
getMyMembership: () => "join",
|
|
1132
|
+
},
|
|
1133
|
+
]);
|
|
1134
|
+
|
|
1135
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1136
|
+
const invites: string[] = [];
|
|
1137
|
+
client.on("room.invite", (roomId) => {
|
|
1138
|
+
invites.push(roomId);
|
|
1139
|
+
});
|
|
1140
|
+
|
|
1141
|
+
await client.start();
|
|
1142
|
+
|
|
1143
|
+
expect(invites).toEqual(["!pending:example.org"]);
|
|
1144
|
+
});
|
|
1145
|
+
});
|
|
1146
|
+
|
|
1147
|
+
describe("MatrixClient crypto bootstrapping", () => {
|
|
1148
|
+
beforeEach(() => {
|
|
1149
|
+
matrixJsClient = createMatrixJsClientStub();
|
|
1150
|
+
lastCreateClientOpts = null;
|
|
1151
|
+
});
|
|
1152
|
+
|
|
1153
|
+
afterEach(() => {
|
|
1154
|
+
vi.useRealTimers();
|
|
1155
|
+
vi.restoreAllMocks();
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
it("passes cryptoDatabasePrefix into initRustCrypto", async () => {
|
|
1159
|
+
matrixJsClient.getCrypto = vi.fn(() => undefined);
|
|
1160
|
+
|
|
1161
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1162
|
+
encryption: true,
|
|
1163
|
+
cryptoDatabasePrefix: "openclaw-matrix-test",
|
|
1164
|
+
});
|
|
1165
|
+
|
|
1166
|
+
await client.start();
|
|
1167
|
+
|
|
1168
|
+
expect(matrixJsClient.initRustCrypto).toHaveBeenCalledWith({
|
|
1169
|
+
cryptoDatabasePrefix: "openclaw-matrix-test",
|
|
1170
|
+
});
|
|
1171
|
+
});
|
|
1172
|
+
|
|
1173
|
+
it("bootstraps cross-signing with setupNewCrossSigning enabled", async () => {
|
|
1174
|
+
const bootstrapCrossSigning = vi.fn(async () => {});
|
|
1175
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1176
|
+
on: vi.fn(),
|
|
1177
|
+
bootstrapCrossSigning,
|
|
1178
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
1179
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
1180
|
+
}));
|
|
1181
|
+
|
|
1182
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1183
|
+
encryption: true,
|
|
1184
|
+
});
|
|
1185
|
+
|
|
1186
|
+
await client.start();
|
|
1187
|
+
|
|
1188
|
+
expect(bootstrapCrossSigning).toHaveBeenCalledWith(
|
|
1189
|
+
expect.objectContaining({
|
|
1190
|
+
authUploadDeviceSigningKeys: expect.any(Function),
|
|
1191
|
+
}),
|
|
1192
|
+
);
|
|
1193
|
+
});
|
|
1194
|
+
|
|
1195
|
+
it("retries bootstrap with forced reset when initial publish/verification is incomplete", async () => {
|
|
1196
|
+
matrixJsClient.getCrypto = vi.fn(() => ({ on: vi.fn() }));
|
|
1197
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1198
|
+
encryption: true,
|
|
1199
|
+
password: "secret-password", // pragma: allowlist secret
|
|
1200
|
+
});
|
|
1201
|
+
const bootstrapSpy = vi
|
|
1202
|
+
.fn()
|
|
1203
|
+
.mockResolvedValueOnce({
|
|
1204
|
+
crossSigningReady: false,
|
|
1205
|
+
crossSigningPublished: false,
|
|
1206
|
+
ownDeviceVerified: false,
|
|
1207
|
+
})
|
|
1208
|
+
.mockResolvedValueOnce({
|
|
1209
|
+
crossSigningReady: true,
|
|
1210
|
+
crossSigningPublished: true,
|
|
1211
|
+
ownDeviceVerified: true,
|
|
1212
|
+
});
|
|
1213
|
+
await (
|
|
1214
|
+
client as unknown as {
|
|
1215
|
+
ensureCryptoSupportInitialized: () => Promise<void>;
|
|
1216
|
+
}
|
|
1217
|
+
).ensureCryptoSupportInitialized();
|
|
1218
|
+
(
|
|
1219
|
+
client as unknown as {
|
|
1220
|
+
cryptoBootstrapper: { bootstrap: typeof bootstrapSpy };
|
|
1221
|
+
}
|
|
1222
|
+
).cryptoBootstrapper.bootstrap = bootstrapSpy;
|
|
1223
|
+
|
|
1224
|
+
await client.start();
|
|
1225
|
+
|
|
1226
|
+
expect(bootstrapSpy).toHaveBeenCalledTimes(2);
|
|
1227
|
+
expect((bootstrapSpy.mock.calls as unknown[][])[1]?.[1] ?? {}).toEqual({
|
|
1228
|
+
forceResetCrossSigning: true,
|
|
1229
|
+
allowSecretStorageRecreateWithoutRecoveryKey: true,
|
|
1230
|
+
strict: true,
|
|
1231
|
+
});
|
|
1232
|
+
});
|
|
1233
|
+
|
|
1234
|
+
it("does not force-reset bootstrap when the device is already signed by its owner", async () => {
|
|
1235
|
+
matrixJsClient.getCrypto = vi.fn(() => ({ on: vi.fn() }));
|
|
1236
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1237
|
+
encryption: true,
|
|
1238
|
+
password: "secret-password", // pragma: allowlist secret
|
|
1239
|
+
});
|
|
1240
|
+
const bootstrapSpy = vi.fn().mockResolvedValue({
|
|
1241
|
+
crossSigningReady: false,
|
|
1242
|
+
crossSigningPublished: false,
|
|
1243
|
+
ownDeviceVerified: true,
|
|
1244
|
+
});
|
|
1245
|
+
await (
|
|
1246
|
+
client as unknown as {
|
|
1247
|
+
ensureCryptoSupportInitialized: () => Promise<void>;
|
|
1248
|
+
}
|
|
1249
|
+
).ensureCryptoSupportInitialized();
|
|
1250
|
+
(
|
|
1251
|
+
client as unknown as {
|
|
1252
|
+
cryptoBootstrapper: { bootstrap: typeof bootstrapSpy };
|
|
1253
|
+
}
|
|
1254
|
+
).cryptoBootstrapper.bootstrap = bootstrapSpy;
|
|
1255
|
+
vi.spyOn(client, "getOwnDeviceVerificationStatus").mockResolvedValue({
|
|
1256
|
+
encryptionEnabled: true,
|
|
1257
|
+
userId: "@bot:example.org",
|
|
1258
|
+
deviceId: "DEVICE123",
|
|
1259
|
+
verified: true,
|
|
1260
|
+
localVerified: true,
|
|
1261
|
+
crossSigningVerified: false,
|
|
1262
|
+
signedByOwner: true,
|
|
1263
|
+
recoveryKeyStored: false,
|
|
1264
|
+
recoveryKeyCreatedAt: null,
|
|
1265
|
+
recoveryKeyId: null,
|
|
1266
|
+
backupVersion: null,
|
|
1267
|
+
backup: {
|
|
1268
|
+
serverVersion: null,
|
|
1269
|
+
activeVersion: null,
|
|
1270
|
+
trusted: null,
|
|
1271
|
+
matchesDecryptionKey: null,
|
|
1272
|
+
decryptionKeyCached: false,
|
|
1273
|
+
keyLoadAttempted: false,
|
|
1274
|
+
keyLoadError: null,
|
|
1275
|
+
},
|
|
1276
|
+
});
|
|
1277
|
+
|
|
1278
|
+
await client.start();
|
|
1279
|
+
|
|
1280
|
+
expect(bootstrapSpy).toHaveBeenCalledTimes(1);
|
|
1281
|
+
expect((bootstrapSpy.mock.calls as unknown[][])[0]?.[1] ?? {}).toEqual({
|
|
1282
|
+
allowAutomaticCrossSigningReset: false,
|
|
1283
|
+
});
|
|
1284
|
+
});
|
|
1285
|
+
|
|
1286
|
+
it("does not force-reset bootstrap when password is unavailable", async () => {
|
|
1287
|
+
matrixJsClient.getCrypto = vi.fn(() => ({ on: vi.fn() }));
|
|
1288
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1289
|
+
encryption: true,
|
|
1290
|
+
});
|
|
1291
|
+
const bootstrapSpy = vi.fn().mockResolvedValue({
|
|
1292
|
+
crossSigningReady: false,
|
|
1293
|
+
crossSigningPublished: false,
|
|
1294
|
+
ownDeviceVerified: false,
|
|
1295
|
+
});
|
|
1296
|
+
await (
|
|
1297
|
+
client as unknown as {
|
|
1298
|
+
ensureCryptoSupportInitialized: () => Promise<void>;
|
|
1299
|
+
}
|
|
1300
|
+
).ensureCryptoSupportInitialized();
|
|
1301
|
+
(
|
|
1302
|
+
client as unknown as {
|
|
1303
|
+
cryptoBootstrapper: { bootstrap: typeof bootstrapSpy };
|
|
1304
|
+
}
|
|
1305
|
+
).cryptoBootstrapper.bootstrap = bootstrapSpy;
|
|
1306
|
+
|
|
1307
|
+
await client.start();
|
|
1308
|
+
|
|
1309
|
+
expect(bootstrapSpy).toHaveBeenCalledTimes(1);
|
|
1310
|
+
});
|
|
1311
|
+
|
|
1312
|
+
it("provides secret storage callbacks and resolves stored recovery key", async () => {
|
|
1313
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "matrix-sdk-test-"));
|
|
1314
|
+
const recoveryKeyPath = path.join(tmpDir, "recovery-key.json");
|
|
1315
|
+
const privateKeyBase64 = Buffer.from([1, 2, 3, 4]).toString("base64");
|
|
1316
|
+
fs.writeFileSync(
|
|
1317
|
+
recoveryKeyPath,
|
|
1318
|
+
JSON.stringify({
|
|
1319
|
+
version: 1,
|
|
1320
|
+
createdAt: new Date().toISOString(),
|
|
1321
|
+
keyId: "SSSSKEY",
|
|
1322
|
+
privateKeyBase64,
|
|
1323
|
+
}),
|
|
1324
|
+
"utf8",
|
|
1325
|
+
);
|
|
1326
|
+
|
|
1327
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1328
|
+
encryption: true,
|
|
1329
|
+
recoveryKeyPath,
|
|
1330
|
+
});
|
|
1331
|
+
expect(client).toBeInstanceOf(MatrixClient);
|
|
1332
|
+
|
|
1333
|
+
const callbacks = (lastCreateClientOpts?.cryptoCallbacks ?? null) as {
|
|
1334
|
+
getSecretStorageKey?: (
|
|
1335
|
+
params: { keys: Record<string, unknown> },
|
|
1336
|
+
name: string,
|
|
1337
|
+
) => Promise<[string, Uint8Array] | null>;
|
|
1338
|
+
} | null;
|
|
1339
|
+
expect(callbacks?.getSecretStorageKey).toBeTypeOf("function");
|
|
1340
|
+
|
|
1341
|
+
const resolved = await callbacks?.getSecretStorageKey?.(
|
|
1342
|
+
{ keys: { SSSSKEY: { algorithm: "m.secret_storage.v1.aes-hmac-sha2" } } },
|
|
1343
|
+
"m.cross_signing.master",
|
|
1344
|
+
);
|
|
1345
|
+
expect(resolved?.[0]).toBe("SSSSKEY");
|
|
1346
|
+
expect(Array.from(resolved?.[1] ?? [])).toEqual([1, 2, 3, 4]);
|
|
1347
|
+
});
|
|
1348
|
+
|
|
1349
|
+
it("provides a matrix-js-sdk logger to createClient", () => {
|
|
1350
|
+
const client = new MatrixClient("https://matrix.example.org", "token");
|
|
1351
|
+
expect(client).toBeInstanceOf(MatrixClient);
|
|
1352
|
+
const logger = (lastCreateClientOpts?.logger ?? null) as {
|
|
1353
|
+
debug?: (...args: unknown[]) => void;
|
|
1354
|
+
getChild?: (namespace: string) => unknown;
|
|
1355
|
+
} | null;
|
|
1356
|
+
expect(logger).not.toBeNull();
|
|
1357
|
+
expect(logger?.debug).toBeTypeOf("function");
|
|
1358
|
+
expect(logger?.getChild).toBeTypeOf("function");
|
|
1359
|
+
});
|
|
1360
|
+
|
|
1361
|
+
it("schedules periodic crypto snapshot persistence with fake timers", async () => {
|
|
1362
|
+
vi.useFakeTimers();
|
|
1363
|
+
const databasesSpy = vi.spyOn(indexedDB, "databases").mockResolvedValue([]);
|
|
1364
|
+
|
|
1365
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1366
|
+
encryption: true,
|
|
1367
|
+
idbSnapshotPath: path.join(os.tmpdir(), "matrix-idb-interval.json"),
|
|
1368
|
+
cryptoDatabasePrefix: "openclaw-matrix-interval",
|
|
1369
|
+
});
|
|
1370
|
+
|
|
1371
|
+
await client.start();
|
|
1372
|
+
const callsAfterStart = databasesSpy.mock.calls.length;
|
|
1373
|
+
|
|
1374
|
+
await vi.advanceTimersByTimeAsync(60_000);
|
|
1375
|
+
await vi.waitFor(() => {
|
|
1376
|
+
expect(databasesSpy.mock.calls.length).toBeGreaterThan(callsAfterStart);
|
|
1377
|
+
});
|
|
1378
|
+
|
|
1379
|
+
client.stop();
|
|
1380
|
+
const callsAfterStop = databasesSpy.mock.calls.length;
|
|
1381
|
+
await vi.advanceTimersByTimeAsync(120_000);
|
|
1382
|
+
expect(databasesSpy.mock.calls.length).toBe(callsAfterStop);
|
|
1383
|
+
});
|
|
1384
|
+
|
|
1385
|
+
it("reports own verification status when crypto marks device as verified", async () => {
|
|
1386
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
1387
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
1388
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1389
|
+
on: vi.fn(),
|
|
1390
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
1391
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
1392
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
1393
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
1394
|
+
isVerified: () => true,
|
|
1395
|
+
localVerified: true,
|
|
1396
|
+
crossSigningVerified: true,
|
|
1397
|
+
signedByOwner: true,
|
|
1398
|
+
})),
|
|
1399
|
+
}));
|
|
1400
|
+
|
|
1401
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1402
|
+
encryption: true,
|
|
1403
|
+
});
|
|
1404
|
+
await client.start();
|
|
1405
|
+
|
|
1406
|
+
const status = await client.getOwnDeviceVerificationStatus();
|
|
1407
|
+
expect(status.encryptionEnabled).toBe(true);
|
|
1408
|
+
expect(status.verified).toBe(true);
|
|
1409
|
+
expect(status.userId).toBe("@bot:example.org");
|
|
1410
|
+
expect(status.deviceId).toBe("DEVICE123");
|
|
1411
|
+
});
|
|
1412
|
+
|
|
1413
|
+
it("does not treat local-only trust as owner verification", async () => {
|
|
1414
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
1415
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
1416
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1417
|
+
on: vi.fn(),
|
|
1418
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
1419
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
1420
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
1421
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
1422
|
+
isVerified: () => true,
|
|
1423
|
+
localVerified: true,
|
|
1424
|
+
crossSigningVerified: false,
|
|
1425
|
+
signedByOwner: false,
|
|
1426
|
+
})),
|
|
1427
|
+
}));
|
|
1428
|
+
|
|
1429
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1430
|
+
encryption: true,
|
|
1431
|
+
});
|
|
1432
|
+
await client.start();
|
|
1433
|
+
|
|
1434
|
+
const status = await client.getOwnDeviceVerificationStatus();
|
|
1435
|
+
expect(status.localVerified).toBe(true);
|
|
1436
|
+
expect(status.crossSigningVerified).toBe(false);
|
|
1437
|
+
expect(status.signedByOwner).toBe(false);
|
|
1438
|
+
expect(status.verified).toBe(false);
|
|
1439
|
+
});
|
|
1440
|
+
|
|
1441
|
+
it("verifies with a provided recovery key and reports success", async () => {
|
|
1442
|
+
const encoded = encodeRecoveryKey(new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 1)));
|
|
1443
|
+
expect(encoded).toBeTypeOf("string");
|
|
1444
|
+
|
|
1445
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
1446
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
1447
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
1448
|
+
const bootstrapCrossSigning = vi.fn(async () => {});
|
|
1449
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
1450
|
+
const getSecretStorageStatus = vi.fn(async () => ({
|
|
1451
|
+
ready: true,
|
|
1452
|
+
defaultKeyId: "SSSSKEY",
|
|
1453
|
+
secretStorageKeyValidityMap: { SSSSKEY: true },
|
|
1454
|
+
}));
|
|
1455
|
+
const getDeviceVerificationStatus = vi.fn(async () => ({
|
|
1456
|
+
isVerified: () => true,
|
|
1457
|
+
localVerified: true,
|
|
1458
|
+
crossSigningVerified: true,
|
|
1459
|
+
signedByOwner: true,
|
|
1460
|
+
}));
|
|
1461
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1462
|
+
on: vi.fn(),
|
|
1463
|
+
bootstrapCrossSigning,
|
|
1464
|
+
bootstrapSecretStorage,
|
|
1465
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
1466
|
+
getSecretStorageStatus,
|
|
1467
|
+
getDeviceVerificationStatus,
|
|
1468
|
+
checkKeyBackupAndEnable,
|
|
1469
|
+
}));
|
|
1470
|
+
|
|
1471
|
+
const recoveryDir = fs.mkdtempSync(path.join(os.tmpdir(), "matrix-sdk-verify-key-"));
|
|
1472
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1473
|
+
encryption: true,
|
|
1474
|
+
recoveryKeyPath: path.join(recoveryDir, "recovery-key.json"),
|
|
1475
|
+
});
|
|
1476
|
+
|
|
1477
|
+
const result = await client.verifyWithRecoveryKey(encoded as string);
|
|
1478
|
+
expect(result.success).toBe(true);
|
|
1479
|
+
expect(result.verified).toBe(true);
|
|
1480
|
+
expect(result.recoveryKeyStored).toBe(true);
|
|
1481
|
+
expect(result.deviceId).toBe("DEVICE123");
|
|
1482
|
+
expect(matrixJsClient.startClient).toHaveBeenCalledTimes(1);
|
|
1483
|
+
expect(bootstrapSecretStorage).toHaveBeenCalled();
|
|
1484
|
+
expect(bootstrapCrossSigning).toHaveBeenCalled();
|
|
1485
|
+
expect(checkKeyBackupAndEnable).toHaveBeenCalledTimes(1);
|
|
1486
|
+
});
|
|
1487
|
+
|
|
1488
|
+
it("fails recovery-key verification when the device is only locally trusted", async () => {
|
|
1489
|
+
const encoded = encodeRecoveryKey(new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 1)));
|
|
1490
|
+
|
|
1491
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
1492
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
1493
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1494
|
+
on: vi.fn(),
|
|
1495
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
1496
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
1497
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
1498
|
+
getSecretStorageStatus: vi.fn(async () => ({
|
|
1499
|
+
ready: true,
|
|
1500
|
+
defaultKeyId: "SSSSKEY",
|
|
1501
|
+
secretStorageKeyValidityMap: { SSSSKEY: true },
|
|
1502
|
+
})),
|
|
1503
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
1504
|
+
isVerified: () => true,
|
|
1505
|
+
localVerified: true,
|
|
1506
|
+
crossSigningVerified: false,
|
|
1507
|
+
signedByOwner: false,
|
|
1508
|
+
})),
|
|
1509
|
+
}));
|
|
1510
|
+
|
|
1511
|
+
const recoveryDir = fs.mkdtempSync(path.join(os.tmpdir(), "matrix-sdk-verify-local-only-"));
|
|
1512
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1513
|
+
encryption: true,
|
|
1514
|
+
recoveryKeyPath: path.join(recoveryDir, "recovery-key.json"),
|
|
1515
|
+
});
|
|
1516
|
+
await client.start();
|
|
1517
|
+
|
|
1518
|
+
const result = await client.verifyWithRecoveryKey(encoded as string);
|
|
1519
|
+
expect(result.success).toBe(false);
|
|
1520
|
+
expect(result.verified).toBe(false);
|
|
1521
|
+
expect(result.error).toContain("not verified by its owner");
|
|
1522
|
+
});
|
|
1523
|
+
|
|
1524
|
+
it("fails recovery-key verification when backup remains untrusted after device verification", async () => {
|
|
1525
|
+
const encoded = encodeRecoveryKey(new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 1)));
|
|
1526
|
+
|
|
1527
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
1528
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
1529
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1530
|
+
on: vi.fn(),
|
|
1531
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
1532
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
1533
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
1534
|
+
getSecretStorageStatus: vi.fn(async () => ({
|
|
1535
|
+
ready: true,
|
|
1536
|
+
defaultKeyId: "SSSSKEY",
|
|
1537
|
+
secretStorageKeyValidityMap: { SSSSKEY: true },
|
|
1538
|
+
})),
|
|
1539
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
1540
|
+
isVerified: () => true,
|
|
1541
|
+
localVerified: true,
|
|
1542
|
+
crossSigningVerified: true,
|
|
1543
|
+
signedByOwner: true,
|
|
1544
|
+
})),
|
|
1545
|
+
checkKeyBackupAndEnable: vi.fn(async () => {}),
|
|
1546
|
+
getActiveSessionBackupVersion: vi.fn(async () => "11"),
|
|
1547
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
1548
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1549
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1550
|
+
auth_data: {},
|
|
1551
|
+
version: "11",
|
|
1552
|
+
})),
|
|
1553
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1554
|
+
trusted: false,
|
|
1555
|
+
matchesDecryptionKey: true,
|
|
1556
|
+
})),
|
|
1557
|
+
}));
|
|
1558
|
+
|
|
1559
|
+
const recoveryDir = fs.mkdtempSync(path.join(os.tmpdir(), "matrix-sdk-verify-untrusted-"));
|
|
1560
|
+
const recoveryKeyPath = path.join(recoveryDir, "recovery-key.json");
|
|
1561
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1562
|
+
encryption: true,
|
|
1563
|
+
recoveryKeyPath,
|
|
1564
|
+
});
|
|
1565
|
+
|
|
1566
|
+
const result = await client.verifyWithRecoveryKey(encoded as string);
|
|
1567
|
+
expect(result.success).toBe(false);
|
|
1568
|
+
expect(result.verified).toBe(true);
|
|
1569
|
+
expect(result.error).toContain("backup signature chain is not trusted");
|
|
1570
|
+
expect(result.recoveryKeyStored).toBe(false);
|
|
1571
|
+
expect(fs.existsSync(recoveryKeyPath)).toBe(false);
|
|
1572
|
+
});
|
|
1573
|
+
|
|
1574
|
+
it("does not overwrite the stored recovery key when recovery-key verification fails", async () => {
|
|
1575
|
+
const previousEncoded = encodeRecoveryKey(
|
|
1576
|
+
new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 5)),
|
|
1577
|
+
);
|
|
1578
|
+
const attemptedEncoded = encodeRecoveryKey(
|
|
1579
|
+
new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 55)),
|
|
1580
|
+
);
|
|
1581
|
+
|
|
1582
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
1583
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
1584
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1585
|
+
on: vi.fn(),
|
|
1586
|
+
bootstrapCrossSigning: vi.fn(async () => {
|
|
1587
|
+
throw new Error("secret storage rejected recovery key");
|
|
1588
|
+
}),
|
|
1589
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
1590
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
1591
|
+
getSecretStorageStatus: vi.fn(async () => ({
|
|
1592
|
+
ready: true,
|
|
1593
|
+
defaultKeyId: "SSSSKEY",
|
|
1594
|
+
secretStorageKeyValidityMap: { SSSSKEY: true },
|
|
1595
|
+
})),
|
|
1596
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
1597
|
+
isVerified: () => false,
|
|
1598
|
+
localVerified: false,
|
|
1599
|
+
crossSigningVerified: false,
|
|
1600
|
+
signedByOwner: false,
|
|
1601
|
+
})),
|
|
1602
|
+
}));
|
|
1603
|
+
|
|
1604
|
+
const recoveryDir = fs.mkdtempSync(path.join(os.tmpdir(), "matrix-sdk-verify-preserve-"));
|
|
1605
|
+
const recoveryKeyPath = path.join(recoveryDir, "recovery-key.json");
|
|
1606
|
+
fs.writeFileSync(
|
|
1607
|
+
recoveryKeyPath,
|
|
1608
|
+
JSON.stringify({
|
|
1609
|
+
version: 1,
|
|
1610
|
+
createdAt: new Date().toISOString(),
|
|
1611
|
+
keyId: "SSSSKEY",
|
|
1612
|
+
encodedPrivateKey: previousEncoded,
|
|
1613
|
+
privateKeyBase64: Buffer.from(
|
|
1614
|
+
new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 5)),
|
|
1615
|
+
).toString("base64"),
|
|
1616
|
+
}),
|
|
1617
|
+
"utf8",
|
|
1618
|
+
);
|
|
1619
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1620
|
+
encryption: true,
|
|
1621
|
+
recoveryKeyPath,
|
|
1622
|
+
});
|
|
1623
|
+
|
|
1624
|
+
const result = await client.verifyWithRecoveryKey(attemptedEncoded as string);
|
|
1625
|
+
|
|
1626
|
+
expect(result.success).toBe(false);
|
|
1627
|
+
expect(result.error).toContain("not verified by its owner");
|
|
1628
|
+
const persisted = JSON.parse(fs.readFileSync(recoveryKeyPath, "utf8")) as {
|
|
1629
|
+
encodedPrivateKey?: string;
|
|
1630
|
+
};
|
|
1631
|
+
expect(persisted.encodedPrivateKey).toBe(previousEncoded);
|
|
1632
|
+
});
|
|
1633
|
+
|
|
1634
|
+
it("reports detailed room-key backup health", async () => {
|
|
1635
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
1636
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
1637
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1638
|
+
on: vi.fn(),
|
|
1639
|
+
getActiveSessionBackupVersion: vi.fn(async () => "11"),
|
|
1640
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1, 2, 3])),
|
|
1641
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1642
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1643
|
+
auth_data: {},
|
|
1644
|
+
version: "11",
|
|
1645
|
+
})),
|
|
1646
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1647
|
+
trusted: true,
|
|
1648
|
+
matchesDecryptionKey: true,
|
|
1649
|
+
})),
|
|
1650
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
1651
|
+
isVerified: () => true,
|
|
1652
|
+
localVerified: true,
|
|
1653
|
+
crossSigningVerified: true,
|
|
1654
|
+
signedByOwner: true,
|
|
1655
|
+
})),
|
|
1656
|
+
}));
|
|
1657
|
+
|
|
1658
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1659
|
+
encryption: true,
|
|
1660
|
+
});
|
|
1661
|
+
vi.spyOn(client, "doRequest").mockResolvedValue({ version: "11" });
|
|
1662
|
+
|
|
1663
|
+
const status = await client.getOwnDeviceVerificationStatus();
|
|
1664
|
+
expect(status.backupVersion).toBe("11");
|
|
1665
|
+
expect(status.backup).toEqual({
|
|
1666
|
+
serverVersion: "11",
|
|
1667
|
+
activeVersion: "11",
|
|
1668
|
+
trusted: true,
|
|
1669
|
+
matchesDecryptionKey: true,
|
|
1670
|
+
decryptionKeyCached: true,
|
|
1671
|
+
keyLoadAttempted: false,
|
|
1672
|
+
keyLoadError: null,
|
|
1673
|
+
});
|
|
1674
|
+
});
|
|
1675
|
+
|
|
1676
|
+
it("tries loading backup keys from secret storage when key is missing from cache", async () => {
|
|
1677
|
+
const getActiveSessionBackupVersion = vi
|
|
1678
|
+
.fn()
|
|
1679
|
+
.mockResolvedValueOnce(null)
|
|
1680
|
+
.mockResolvedValueOnce("9");
|
|
1681
|
+
const getSessionBackupPrivateKey = vi
|
|
1682
|
+
.fn()
|
|
1683
|
+
.mockResolvedValueOnce(null)
|
|
1684
|
+
.mockResolvedValueOnce(new Uint8Array([1]));
|
|
1685
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi.fn(async () => {});
|
|
1686
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1687
|
+
on: vi.fn(),
|
|
1688
|
+
getActiveSessionBackupVersion,
|
|
1689
|
+
getSessionBackupPrivateKey,
|
|
1690
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
1691
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1692
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1693
|
+
auth_data: {},
|
|
1694
|
+
version: "9",
|
|
1695
|
+
})),
|
|
1696
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1697
|
+
trusted: true,
|
|
1698
|
+
matchesDecryptionKey: true,
|
|
1699
|
+
})),
|
|
1700
|
+
}));
|
|
1701
|
+
|
|
1702
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1703
|
+
encryption: true,
|
|
1704
|
+
});
|
|
1705
|
+
|
|
1706
|
+
const backup = await client.getRoomKeyBackupStatus();
|
|
1707
|
+
expect(backup).toMatchObject({
|
|
1708
|
+
serverVersion: "9",
|
|
1709
|
+
activeVersion: "9",
|
|
1710
|
+
trusted: true,
|
|
1711
|
+
matchesDecryptionKey: true,
|
|
1712
|
+
decryptionKeyCached: true,
|
|
1713
|
+
keyLoadAttempted: true,
|
|
1714
|
+
keyLoadError: null,
|
|
1715
|
+
});
|
|
1716
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
1717
|
+
});
|
|
1718
|
+
|
|
1719
|
+
it("reloads backup keys from secret storage when the cached key mismatches the active backup", async () => {
|
|
1720
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi.fn(async () => {});
|
|
1721
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
1722
|
+
const isKeyBackupTrusted = vi
|
|
1723
|
+
.fn()
|
|
1724
|
+
.mockResolvedValueOnce({
|
|
1725
|
+
trusted: true,
|
|
1726
|
+
matchesDecryptionKey: false,
|
|
1727
|
+
})
|
|
1728
|
+
.mockResolvedValueOnce({
|
|
1729
|
+
trusted: true,
|
|
1730
|
+
matchesDecryptionKey: true,
|
|
1731
|
+
});
|
|
1732
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1733
|
+
on: vi.fn(),
|
|
1734
|
+
getActiveSessionBackupVersion: vi.fn(async () => "49262"),
|
|
1735
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
1736
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
1737
|
+
checkKeyBackupAndEnable,
|
|
1738
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1739
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1740
|
+
auth_data: {},
|
|
1741
|
+
version: "49262",
|
|
1742
|
+
})),
|
|
1743
|
+
isKeyBackupTrusted,
|
|
1744
|
+
}));
|
|
1745
|
+
|
|
1746
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1747
|
+
encryption: true,
|
|
1748
|
+
});
|
|
1749
|
+
|
|
1750
|
+
const backup = await client.getRoomKeyBackupStatus();
|
|
1751
|
+
expect(backup).toMatchObject({
|
|
1752
|
+
serverVersion: "49262",
|
|
1753
|
+
activeVersion: "49262",
|
|
1754
|
+
trusted: true,
|
|
1755
|
+
matchesDecryptionKey: true,
|
|
1756
|
+
decryptionKeyCached: true,
|
|
1757
|
+
keyLoadAttempted: true,
|
|
1758
|
+
keyLoadError: null,
|
|
1759
|
+
});
|
|
1760
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
1761
|
+
expect(checkKeyBackupAndEnable).toHaveBeenCalledTimes(1);
|
|
1762
|
+
});
|
|
1763
|
+
|
|
1764
|
+
it("reports why backup key loading failed during status checks", async () => {
|
|
1765
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi.fn(async () => {
|
|
1766
|
+
throw new Error("secret storage key is not available");
|
|
1767
|
+
});
|
|
1768
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1769
|
+
on: vi.fn(),
|
|
1770
|
+
getActiveSessionBackupVersion: vi.fn(async () => null),
|
|
1771
|
+
getSessionBackupPrivateKey: vi.fn(async () => null),
|
|
1772
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
1773
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1774
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1775
|
+
auth_data: {},
|
|
1776
|
+
version: "9",
|
|
1777
|
+
})),
|
|
1778
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1779
|
+
trusted: true,
|
|
1780
|
+
matchesDecryptionKey: false,
|
|
1781
|
+
})),
|
|
1782
|
+
}));
|
|
1783
|
+
|
|
1784
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1785
|
+
encryption: true,
|
|
1786
|
+
});
|
|
1787
|
+
|
|
1788
|
+
const backup = await client.getRoomKeyBackupStatus();
|
|
1789
|
+
expect(backup.keyLoadAttempted).toBe(true);
|
|
1790
|
+
expect(backup.keyLoadError).toContain("secret storage key is not available");
|
|
1791
|
+
expect(backup.decryptionKeyCached).toBe(false);
|
|
1792
|
+
});
|
|
1793
|
+
|
|
1794
|
+
it("restores room keys from backup after loading key from secret storage", async () => {
|
|
1795
|
+
const getActiveSessionBackupVersion = vi
|
|
1796
|
+
.fn()
|
|
1797
|
+
.mockResolvedValueOnce(null)
|
|
1798
|
+
.mockResolvedValueOnce("9")
|
|
1799
|
+
.mockResolvedValue("9");
|
|
1800
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi.fn(async () => {});
|
|
1801
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
1802
|
+
const restoreKeyBackup = vi.fn(async () => ({ imported: 4, total: 10 }));
|
|
1803
|
+
const crypto = {
|
|
1804
|
+
on: vi.fn(),
|
|
1805
|
+
getActiveSessionBackupVersion,
|
|
1806
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
1807
|
+
checkKeyBackupAndEnable,
|
|
1808
|
+
restoreKeyBackup,
|
|
1809
|
+
getSessionBackupPrivateKey: vi
|
|
1810
|
+
.fn()
|
|
1811
|
+
.mockResolvedValueOnce(null)
|
|
1812
|
+
.mockResolvedValue(new Uint8Array([1])),
|
|
1813
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1814
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1815
|
+
auth_data: {},
|
|
1816
|
+
version: "9",
|
|
1817
|
+
})),
|
|
1818
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1819
|
+
trusted: true,
|
|
1820
|
+
matchesDecryptionKey: true,
|
|
1821
|
+
})),
|
|
1822
|
+
};
|
|
1823
|
+
matrixJsClient.getCrypto = vi.fn(() => crypto);
|
|
1824
|
+
|
|
1825
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1826
|
+
encryption: true,
|
|
1827
|
+
});
|
|
1828
|
+
vi.spyOn(client, "doRequest").mockResolvedValue({ version: "9" });
|
|
1829
|
+
|
|
1830
|
+
const result = await client.restoreRoomKeyBackup();
|
|
1831
|
+
expect(result.success).toBe(true);
|
|
1832
|
+
expect(result.backupVersion).toBe("9");
|
|
1833
|
+
expect(result.imported).toBe(4);
|
|
1834
|
+
expect(result.total).toBe(10);
|
|
1835
|
+
expect(result.loadedFromSecretStorage).toBe(true);
|
|
1836
|
+
expect(matrixJsClient.startClient).toHaveBeenCalledTimes(1);
|
|
1837
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
1838
|
+
expect(checkKeyBackupAndEnable).toHaveBeenCalledTimes(1);
|
|
1839
|
+
expect(restoreKeyBackup).toHaveBeenCalledTimes(1);
|
|
1840
|
+
});
|
|
1841
|
+
|
|
1842
|
+
it("activates backup after loading the key from secret storage before restore", async () => {
|
|
1843
|
+
const getActiveSessionBackupVersion = vi
|
|
1844
|
+
.fn()
|
|
1845
|
+
.mockResolvedValueOnce(null)
|
|
1846
|
+
.mockResolvedValueOnce("5256")
|
|
1847
|
+
.mockResolvedValue("5256");
|
|
1848
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi.fn(async () => {});
|
|
1849
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
1850
|
+
const restoreKeyBackup = vi.fn(async () => ({ imported: 0, total: 0 }));
|
|
1851
|
+
const crypto = {
|
|
1852
|
+
on: vi.fn(),
|
|
1853
|
+
getActiveSessionBackupVersion,
|
|
1854
|
+
getSessionBackupPrivateKey: vi
|
|
1855
|
+
.fn()
|
|
1856
|
+
.mockResolvedValueOnce(null)
|
|
1857
|
+
.mockResolvedValue(new Uint8Array([1])),
|
|
1858
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
1859
|
+
checkKeyBackupAndEnable,
|
|
1860
|
+
restoreKeyBackup,
|
|
1861
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1862
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1863
|
+
auth_data: {},
|
|
1864
|
+
version: "5256",
|
|
1865
|
+
})),
|
|
1866
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1867
|
+
trusted: true,
|
|
1868
|
+
matchesDecryptionKey: true,
|
|
1869
|
+
})),
|
|
1870
|
+
};
|
|
1871
|
+
matrixJsClient.getCrypto = vi.fn(() => crypto);
|
|
1872
|
+
|
|
1873
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1874
|
+
encryption: true,
|
|
1875
|
+
});
|
|
1876
|
+
vi.spyOn(client, "doRequest").mockResolvedValue({ version: "5256" });
|
|
1877
|
+
|
|
1878
|
+
const result = await client.restoreRoomKeyBackup();
|
|
1879
|
+
expect(result.success).toBe(true);
|
|
1880
|
+
expect(result.backupVersion).toBe("5256");
|
|
1881
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
1882
|
+
expect(checkKeyBackupAndEnable).toHaveBeenCalledTimes(1);
|
|
1883
|
+
expect(restoreKeyBackup).toHaveBeenCalledTimes(1);
|
|
1884
|
+
});
|
|
1885
|
+
|
|
1886
|
+
it("fails restore when backup key cannot be loaded on this device", async () => {
|
|
1887
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1888
|
+
on: vi.fn(),
|
|
1889
|
+
getActiveSessionBackupVersion: vi.fn(async () => null),
|
|
1890
|
+
getSessionBackupPrivateKey: vi.fn(async () => null),
|
|
1891
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1892
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1893
|
+
auth_data: {},
|
|
1894
|
+
version: "3",
|
|
1895
|
+
})),
|
|
1896
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1897
|
+
trusted: true,
|
|
1898
|
+
matchesDecryptionKey: false,
|
|
1899
|
+
})),
|
|
1900
|
+
}));
|
|
1901
|
+
|
|
1902
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1903
|
+
encryption: true,
|
|
1904
|
+
});
|
|
1905
|
+
vi.spyOn(client, "doRequest").mockResolvedValue({ version: "3" });
|
|
1906
|
+
|
|
1907
|
+
const result = await client.restoreRoomKeyBackup();
|
|
1908
|
+
expect(result.success).toBe(false);
|
|
1909
|
+
expect(result.error).toContain("backup decryption key could not be loaded from secret storage");
|
|
1910
|
+
expect(result.backupVersion).toBe("3");
|
|
1911
|
+
expect(result.backup.matchesDecryptionKey).toBe(false);
|
|
1912
|
+
});
|
|
1913
|
+
|
|
1914
|
+
it("reloads the matching backup key before restore when the cached key mismatches", async () => {
|
|
1915
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi.fn(async () => {});
|
|
1916
|
+
const restoreKeyBackup = vi.fn(async () => ({ imported: 6, total: 9 }));
|
|
1917
|
+
const isKeyBackupTrusted = vi
|
|
1918
|
+
.fn()
|
|
1919
|
+
.mockResolvedValueOnce({
|
|
1920
|
+
trusted: true,
|
|
1921
|
+
matchesDecryptionKey: false,
|
|
1922
|
+
})
|
|
1923
|
+
.mockResolvedValueOnce({
|
|
1924
|
+
trusted: true,
|
|
1925
|
+
matchesDecryptionKey: true,
|
|
1926
|
+
})
|
|
1927
|
+
.mockResolvedValueOnce({
|
|
1928
|
+
trusted: true,
|
|
1929
|
+
matchesDecryptionKey: true,
|
|
1930
|
+
});
|
|
1931
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1932
|
+
on: vi.fn(),
|
|
1933
|
+
getActiveSessionBackupVersion: vi.fn(async () => "49262"),
|
|
1934
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
1935
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
1936
|
+
checkKeyBackupAndEnable: vi.fn(async () => {}),
|
|
1937
|
+
restoreKeyBackup,
|
|
1938
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1939
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1940
|
+
auth_data: {},
|
|
1941
|
+
version: "49262",
|
|
1942
|
+
})),
|
|
1943
|
+
isKeyBackupTrusted,
|
|
1944
|
+
}));
|
|
1945
|
+
|
|
1946
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1947
|
+
encryption: true,
|
|
1948
|
+
});
|
|
1949
|
+
|
|
1950
|
+
const result = await client.restoreRoomKeyBackup();
|
|
1951
|
+
|
|
1952
|
+
expect(result.success).toBe(true);
|
|
1953
|
+
expect(result.backupVersion).toBe("49262");
|
|
1954
|
+
expect(result.imported).toBe(6);
|
|
1955
|
+
expect(result.total).toBe(9);
|
|
1956
|
+
expect(result.loadedFromSecretStorage).toBe(true);
|
|
1957
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
1958
|
+
expect(restoreKeyBackup).toHaveBeenCalledTimes(1);
|
|
1959
|
+
});
|
|
1960
|
+
|
|
1961
|
+
it("resets the current room-key backup and creates a fresh trusted version", async () => {
|
|
1962
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
1963
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
1964
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
1965
|
+
on: vi.fn(),
|
|
1966
|
+
bootstrapSecretStorage,
|
|
1967
|
+
checkKeyBackupAndEnable,
|
|
1968
|
+
getActiveSessionBackupVersion: vi.fn(async () => "21869"),
|
|
1969
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
1970
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
1971
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
1972
|
+
auth_data: {},
|
|
1973
|
+
version: "21869",
|
|
1974
|
+
})),
|
|
1975
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
1976
|
+
trusted: true,
|
|
1977
|
+
matchesDecryptionKey: true,
|
|
1978
|
+
})),
|
|
1979
|
+
}));
|
|
1980
|
+
|
|
1981
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
1982
|
+
encryption: true,
|
|
1983
|
+
});
|
|
1984
|
+
vi.spyOn(client, "doRequest").mockImplementation(async (method, endpoint) => {
|
|
1985
|
+
if (method === "GET" && endpoint.includes("/room_keys/version")) {
|
|
1986
|
+
return { version: "21868" };
|
|
1987
|
+
}
|
|
1988
|
+
if (method === "DELETE" && endpoint.includes("/room_keys/version/21868")) {
|
|
1989
|
+
return {};
|
|
1990
|
+
}
|
|
1991
|
+
return {};
|
|
1992
|
+
});
|
|
1993
|
+
|
|
1994
|
+
const result = await client.resetRoomKeyBackup();
|
|
1995
|
+
|
|
1996
|
+
expect(result.success).toBe(true);
|
|
1997
|
+
expect(result.previousVersion).toBe("21868");
|
|
1998
|
+
expect(result.deletedVersion).toBe("21868");
|
|
1999
|
+
expect(result.createdVersion).toBe("21869");
|
|
2000
|
+
expect(bootstrapSecretStorage).toHaveBeenCalledWith(
|
|
2001
|
+
expect.objectContaining({ setupNewKeyBackup: true }),
|
|
2002
|
+
);
|
|
2003
|
+
expect(checkKeyBackupAndEnable).toHaveBeenCalledTimes(1);
|
|
2004
|
+
});
|
|
2005
|
+
|
|
2006
|
+
it("reloads the new backup decryption key after reset when the old cached key mismatches", async () => {
|
|
2007
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
2008
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
2009
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi.fn(async () => {});
|
|
2010
|
+
const isKeyBackupTrusted = vi
|
|
2011
|
+
.fn()
|
|
2012
|
+
.mockResolvedValueOnce({
|
|
2013
|
+
trusted: true,
|
|
2014
|
+
matchesDecryptionKey: false,
|
|
2015
|
+
})
|
|
2016
|
+
.mockResolvedValueOnce({
|
|
2017
|
+
trusted: true,
|
|
2018
|
+
matchesDecryptionKey: true,
|
|
2019
|
+
});
|
|
2020
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2021
|
+
on: vi.fn(),
|
|
2022
|
+
bootstrapSecretStorage,
|
|
2023
|
+
checkKeyBackupAndEnable,
|
|
2024
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
2025
|
+
getActiveSessionBackupVersion: vi.fn(async () => "49262"),
|
|
2026
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
2027
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2028
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2029
|
+
auth_data: {},
|
|
2030
|
+
version: "49262",
|
|
2031
|
+
})),
|
|
2032
|
+
isKeyBackupTrusted,
|
|
2033
|
+
}));
|
|
2034
|
+
|
|
2035
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2036
|
+
encryption: true,
|
|
2037
|
+
});
|
|
2038
|
+
vi.spyOn(client, "doRequest").mockImplementation(async (method, endpoint) => {
|
|
2039
|
+
if (method === "GET" && endpoint.includes("/room_keys/version")) {
|
|
2040
|
+
return { version: "22245" };
|
|
2041
|
+
}
|
|
2042
|
+
if (method === "DELETE" && endpoint.includes("/room_keys/version/22245")) {
|
|
2043
|
+
return {};
|
|
2044
|
+
}
|
|
2045
|
+
return {};
|
|
2046
|
+
});
|
|
2047
|
+
|
|
2048
|
+
const result = await client.resetRoomKeyBackup();
|
|
2049
|
+
|
|
2050
|
+
expect(result.success).toBe(true);
|
|
2051
|
+
expect(result.createdVersion).toBe("49262");
|
|
2052
|
+
expect(result.backup.matchesDecryptionKey).toBe(true);
|
|
2053
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
2054
|
+
expect(checkKeyBackupAndEnable).toHaveBeenCalledTimes(2);
|
|
2055
|
+
});
|
|
2056
|
+
|
|
2057
|
+
it("fails reset when the recreated backup still does not match the local decryption key", async () => {
|
|
2058
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2059
|
+
on: vi.fn(),
|
|
2060
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
2061
|
+
checkKeyBackupAndEnable: vi.fn(async () => {}),
|
|
2062
|
+
getActiveSessionBackupVersion: vi.fn(async () => "21868"),
|
|
2063
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
2064
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2065
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2066
|
+
auth_data: {},
|
|
2067
|
+
version: "21868",
|
|
2068
|
+
})),
|
|
2069
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2070
|
+
trusted: true,
|
|
2071
|
+
matchesDecryptionKey: false,
|
|
2072
|
+
})),
|
|
2073
|
+
}));
|
|
2074
|
+
|
|
2075
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2076
|
+
encryption: true,
|
|
2077
|
+
});
|
|
2078
|
+
vi.spyOn(client, "doRequest").mockImplementation(async (method, endpoint) => {
|
|
2079
|
+
if (method === "GET" && endpoint.includes("/room_keys/version")) {
|
|
2080
|
+
return { version: "21868" };
|
|
2081
|
+
}
|
|
2082
|
+
if (method === "DELETE" && endpoint.includes("/room_keys/version/21868")) {
|
|
2083
|
+
return {};
|
|
2084
|
+
}
|
|
2085
|
+
return {};
|
|
2086
|
+
});
|
|
2087
|
+
|
|
2088
|
+
const result = await client.resetRoomKeyBackup();
|
|
2089
|
+
|
|
2090
|
+
expect(result.success).toBe(false);
|
|
2091
|
+
expect(result.error).toContain("does not have the matching backup decryption key");
|
|
2092
|
+
expect(result.createdVersion).toBe("21868");
|
|
2093
|
+
expect(result.backup.matchesDecryptionKey).toBe(false);
|
|
2094
|
+
});
|
|
2095
|
+
|
|
2096
|
+
it("forces SSSS recreation when backup-secret access fails with bad MAC before reset", async () => {
|
|
2097
|
+
// Simulates the state after a cross-signing bootstrap that recreated SSSS but left the
|
|
2098
|
+
// old m.megolm_backup.v1 SSSS entry (encrypted with the old key) on the homeserver.
|
|
2099
|
+
// The reset preflight now probes backup-secret access directly, so a missing cached
|
|
2100
|
+
// key plus a repairable secret-storage load failure should force SSSS recreation.
|
|
2101
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
2102
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
2103
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi
|
|
2104
|
+
.fn()
|
|
2105
|
+
.mockRejectedValueOnce(new Error("Error decrypting secret m.megolm_backup.v1: bad MAC"));
|
|
2106
|
+
const getSessionBackupPrivateKey = vi
|
|
2107
|
+
.fn()
|
|
2108
|
+
.mockResolvedValueOnce(null)
|
|
2109
|
+
.mockResolvedValue(new Uint8Array([1]));
|
|
2110
|
+
const getSecretStorageStatus = vi.fn(async () => ({
|
|
2111
|
+
ready: true,
|
|
2112
|
+
defaultKeyId: "key-new",
|
|
2113
|
+
}));
|
|
2114
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2115
|
+
on: vi.fn(),
|
|
2116
|
+
bootstrapSecretStorage,
|
|
2117
|
+
checkKeyBackupAndEnable,
|
|
2118
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
2119
|
+
getSessionBackupPrivateKey,
|
|
2120
|
+
getSecretStorageStatus,
|
|
2121
|
+
getActiveSessionBackupVersion: vi.fn(async () => "22000"),
|
|
2122
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2123
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2124
|
+
auth_data: {},
|
|
2125
|
+
version: "22000",
|
|
2126
|
+
})),
|
|
2127
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2128
|
+
trusted: true,
|
|
2129
|
+
matchesDecryptionKey: true,
|
|
2130
|
+
})),
|
|
2131
|
+
}));
|
|
2132
|
+
|
|
2133
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2134
|
+
encryption: true,
|
|
2135
|
+
});
|
|
2136
|
+
vi.spyOn(client, "doRequest").mockImplementation(async (method, endpoint) => {
|
|
2137
|
+
if (method === "GET" && endpoint.includes("/room_keys/version")) {
|
|
2138
|
+
return { version: "21999" };
|
|
2139
|
+
}
|
|
2140
|
+
if (method === "DELETE" && endpoint.includes("/room_keys/version/21999")) {
|
|
2141
|
+
return {};
|
|
2142
|
+
}
|
|
2143
|
+
return {};
|
|
2144
|
+
});
|
|
2145
|
+
|
|
2146
|
+
const result = await client.resetRoomKeyBackup();
|
|
2147
|
+
|
|
2148
|
+
expect(result.success).toBe(true);
|
|
2149
|
+
expect(result.createdVersion).toBe("22000");
|
|
2150
|
+
// bootstrapSecretStorage must have been called with setupNewSecretStorage: true
|
|
2151
|
+
// because the pre-reset bad MAC status triggered forceNewSecretStorage.
|
|
2152
|
+
expect(bootstrapSecretStorage).toHaveBeenCalledWith(
|
|
2153
|
+
expect.objectContaining({
|
|
2154
|
+
setupNewKeyBackup: true,
|
|
2155
|
+
setupNewSecretStorage: true,
|
|
2156
|
+
}),
|
|
2157
|
+
);
|
|
2158
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
2159
|
+
});
|
|
2160
|
+
|
|
2161
|
+
it("forces SSSS recreation when backup-secret access is broken even without a current server backup", async () => {
|
|
2162
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
2163
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
2164
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi
|
|
2165
|
+
.fn()
|
|
2166
|
+
.mockRejectedValueOnce(new Error("Error decrypting secret m.megolm_backup.v1: bad MAC"));
|
|
2167
|
+
const getSessionBackupPrivateKey = vi
|
|
2168
|
+
.fn()
|
|
2169
|
+
.mockResolvedValueOnce(null)
|
|
2170
|
+
.mockResolvedValue(new Uint8Array([1]));
|
|
2171
|
+
const getActiveSessionBackupVersion = vi
|
|
2172
|
+
.fn()
|
|
2173
|
+
.mockResolvedValueOnce(null)
|
|
2174
|
+
.mockResolvedValue("22001");
|
|
2175
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2176
|
+
on: vi.fn(),
|
|
2177
|
+
bootstrapSecretStorage,
|
|
2178
|
+
checkKeyBackupAndEnable,
|
|
2179
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
2180
|
+
getActiveSessionBackupVersion,
|
|
2181
|
+
getSessionBackupPrivateKey,
|
|
2182
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2183
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2184
|
+
auth_data: {},
|
|
2185
|
+
version: "22001",
|
|
2186
|
+
})),
|
|
2187
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2188
|
+
trusted: true,
|
|
2189
|
+
matchesDecryptionKey: true,
|
|
2190
|
+
})),
|
|
2191
|
+
}));
|
|
2192
|
+
|
|
2193
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2194
|
+
encryption: true,
|
|
2195
|
+
});
|
|
2196
|
+
const doRequest = vi.spyOn(client, "doRequest").mockImplementation(async (method, endpoint) => {
|
|
2197
|
+
if (method === "GET" && endpoint.includes("/room_keys/version")) {
|
|
2198
|
+
return {};
|
|
2199
|
+
}
|
|
2200
|
+
return {};
|
|
2201
|
+
});
|
|
2202
|
+
|
|
2203
|
+
const result = await client.resetRoomKeyBackup();
|
|
2204
|
+
|
|
2205
|
+
expect(result.success).toBe(true);
|
|
2206
|
+
expect(result.previousVersion).toBe(null);
|
|
2207
|
+
expect(result.deletedVersion).toBe(null);
|
|
2208
|
+
expect(result.createdVersion).toBe("22001");
|
|
2209
|
+
expect(bootstrapSecretStorage).toHaveBeenCalledWith(
|
|
2210
|
+
expect.objectContaining({
|
|
2211
|
+
setupNewKeyBackup: true,
|
|
2212
|
+
setupNewSecretStorage: true,
|
|
2213
|
+
}),
|
|
2214
|
+
);
|
|
2215
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
2216
|
+
expect(doRequest).not.toHaveBeenCalledWith(
|
|
2217
|
+
"DELETE",
|
|
2218
|
+
expect.stringContaining("/room_keys/version/"),
|
|
2219
|
+
);
|
|
2220
|
+
});
|
|
2221
|
+
|
|
2222
|
+
it("forces SSSS recreation when backup-secret access returns a falsey callback error before reset", async () => {
|
|
2223
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
2224
|
+
const checkKeyBackupAndEnable = vi.fn(async () => {});
|
|
2225
|
+
const loadSessionBackupPrivateKeyFromSecretStorage = vi
|
|
2226
|
+
.fn()
|
|
2227
|
+
.mockRejectedValueOnce(new Error("getSecretStorageKey callback returned falsey"));
|
|
2228
|
+
const getSessionBackupPrivateKey = vi
|
|
2229
|
+
.fn()
|
|
2230
|
+
.mockResolvedValueOnce(null)
|
|
2231
|
+
.mockResolvedValue(new Uint8Array([1]));
|
|
2232
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2233
|
+
on: vi.fn(),
|
|
2234
|
+
bootstrapSecretStorage,
|
|
2235
|
+
checkKeyBackupAndEnable,
|
|
2236
|
+
loadSessionBackupPrivateKeyFromSecretStorage,
|
|
2237
|
+
getActiveSessionBackupVersion: vi.fn(async () => "22002"),
|
|
2238
|
+
getSessionBackupPrivateKey,
|
|
2239
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2240
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2241
|
+
auth_data: {},
|
|
2242
|
+
version: "22002",
|
|
2243
|
+
})),
|
|
2244
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2245
|
+
trusted: true,
|
|
2246
|
+
matchesDecryptionKey: true,
|
|
2247
|
+
})),
|
|
2248
|
+
}));
|
|
2249
|
+
|
|
2250
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2251
|
+
encryption: true,
|
|
2252
|
+
});
|
|
2253
|
+
vi.spyOn(client, "doRequest").mockImplementation(async (method, endpoint) => {
|
|
2254
|
+
if (method === "GET" && endpoint.includes("/room_keys/version")) {
|
|
2255
|
+
return { version: "22000" };
|
|
2256
|
+
}
|
|
2257
|
+
if (method === "DELETE" && endpoint.includes("/room_keys/version/22000")) {
|
|
2258
|
+
return {};
|
|
2259
|
+
}
|
|
2260
|
+
return {};
|
|
2261
|
+
});
|
|
2262
|
+
|
|
2263
|
+
const result = await client.resetRoomKeyBackup();
|
|
2264
|
+
|
|
2265
|
+
expect(result.success).toBe(true);
|
|
2266
|
+
expect(result.createdVersion).toBe("22002");
|
|
2267
|
+
expect(bootstrapSecretStorage).toHaveBeenCalledWith(
|
|
2268
|
+
expect.objectContaining({
|
|
2269
|
+
setupNewKeyBackup: true,
|
|
2270
|
+
setupNewSecretStorage: true,
|
|
2271
|
+
}),
|
|
2272
|
+
);
|
|
2273
|
+
expect(loadSessionBackupPrivateKeyFromSecretStorage).toHaveBeenCalledTimes(1);
|
|
2274
|
+
});
|
|
2275
|
+
|
|
2276
|
+
it("reports bootstrap failure when cross-signing keys are not published", async () => {
|
|
2277
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
2278
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
2279
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2280
|
+
on: vi.fn(),
|
|
2281
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
2282
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
2283
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
2284
|
+
isCrossSigningReady: vi.fn(async () => false),
|
|
2285
|
+
userHasCrossSigningKeys: vi.fn(async () => false),
|
|
2286
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
2287
|
+
isVerified: () => true,
|
|
2288
|
+
localVerified: true,
|
|
2289
|
+
crossSigningVerified: true,
|
|
2290
|
+
signedByOwner: true,
|
|
2291
|
+
})),
|
|
2292
|
+
}));
|
|
2293
|
+
|
|
2294
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2295
|
+
encryption: true,
|
|
2296
|
+
});
|
|
2297
|
+
vi.spyOn(client, "getOwnCrossSigningPublicationStatus").mockResolvedValue({
|
|
2298
|
+
userId: "@bot:example.org",
|
|
2299
|
+
masterKeyPublished: false,
|
|
2300
|
+
selfSigningKeyPublished: false,
|
|
2301
|
+
userSigningKeyPublished: false,
|
|
2302
|
+
published: false,
|
|
2303
|
+
});
|
|
2304
|
+
|
|
2305
|
+
const result = await client.bootstrapOwnDeviceVerification();
|
|
2306
|
+
expect(result.success).toBe(false);
|
|
2307
|
+
expect(result.error).toContain(
|
|
2308
|
+
"Cross-signing bootstrap finished but server keys are still not published",
|
|
2309
|
+
);
|
|
2310
|
+
expect(matrixJsClient.startClient).toHaveBeenCalledTimes(1);
|
|
2311
|
+
});
|
|
2312
|
+
|
|
2313
|
+
it("reports bootstrap success when own device is verified and keys are published", async () => {
|
|
2314
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
2315
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
2316
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2317
|
+
on: vi.fn(),
|
|
2318
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
2319
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
2320
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
2321
|
+
isCrossSigningReady: vi.fn(async () => true),
|
|
2322
|
+
userHasCrossSigningKeys: vi.fn(async () => true),
|
|
2323
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
2324
|
+
isVerified: () => true,
|
|
2325
|
+
localVerified: true,
|
|
2326
|
+
crossSigningVerified: true,
|
|
2327
|
+
signedByOwner: true,
|
|
2328
|
+
})),
|
|
2329
|
+
getActiveSessionBackupVersion: vi.fn(async () => "9"),
|
|
2330
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
2331
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2332
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2333
|
+
auth_data: {},
|
|
2334
|
+
version: "9",
|
|
2335
|
+
})),
|
|
2336
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2337
|
+
trusted: true,
|
|
2338
|
+
matchesDecryptionKey: true,
|
|
2339
|
+
})),
|
|
2340
|
+
}));
|
|
2341
|
+
|
|
2342
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2343
|
+
encryption: true,
|
|
2344
|
+
});
|
|
2345
|
+
vi.spyOn(client, "getOwnCrossSigningPublicationStatus").mockResolvedValue({
|
|
2346
|
+
userId: "@bot:example.org",
|
|
2347
|
+
masterKeyPublished: true,
|
|
2348
|
+
selfSigningKeyPublished: true,
|
|
2349
|
+
userSigningKeyPublished: true,
|
|
2350
|
+
published: true,
|
|
2351
|
+
});
|
|
2352
|
+
vi.spyOn(client, "doRequest").mockResolvedValue({ version: "9" });
|
|
2353
|
+
|
|
2354
|
+
const result = await client.bootstrapOwnDeviceVerification();
|
|
2355
|
+
expect(result.success).toBe(true);
|
|
2356
|
+
expect(result.verification.verified).toBe(true);
|
|
2357
|
+
expect(result.crossSigning.published).toBe(true);
|
|
2358
|
+
expect(result.cryptoBootstrap).not.toBeNull();
|
|
2359
|
+
});
|
|
2360
|
+
|
|
2361
|
+
it("reports bootstrap failure when the device is only locally trusted", async () => {
|
|
2362
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
2363
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
2364
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2365
|
+
on: vi.fn(),
|
|
2366
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
2367
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
2368
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
2369
|
+
isCrossSigningReady: vi.fn(async () => true),
|
|
2370
|
+
userHasCrossSigningKeys: vi.fn(async () => true),
|
|
2371
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
2372
|
+
isVerified: () => true,
|
|
2373
|
+
localVerified: true,
|
|
2374
|
+
crossSigningVerified: false,
|
|
2375
|
+
signedByOwner: false,
|
|
2376
|
+
})),
|
|
2377
|
+
}));
|
|
2378
|
+
|
|
2379
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2380
|
+
encryption: true,
|
|
2381
|
+
});
|
|
2382
|
+
vi.spyOn(client, "getOwnCrossSigningPublicationStatus").mockResolvedValue({
|
|
2383
|
+
userId: "@bot:example.org",
|
|
2384
|
+
masterKeyPublished: true,
|
|
2385
|
+
selfSigningKeyPublished: true,
|
|
2386
|
+
userSigningKeyPublished: true,
|
|
2387
|
+
published: true,
|
|
2388
|
+
});
|
|
2389
|
+
|
|
2390
|
+
const result = await client.bootstrapOwnDeviceVerification();
|
|
2391
|
+
expect(result.success).toBe(false);
|
|
2392
|
+
expect(result.verification.localVerified).toBe(true);
|
|
2393
|
+
expect(result.verification.signedByOwner).toBe(false);
|
|
2394
|
+
expect(result.error).toContain("not verified by its owner after bootstrap");
|
|
2395
|
+
});
|
|
2396
|
+
|
|
2397
|
+
it("creates a key backup during bootstrap when none exists on the server", async () => {
|
|
2398
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
2399
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
2400
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
2401
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2402
|
+
on: vi.fn(),
|
|
2403
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
2404
|
+
bootstrapSecretStorage,
|
|
2405
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
2406
|
+
isCrossSigningReady: vi.fn(async () => true),
|
|
2407
|
+
userHasCrossSigningKeys: vi.fn(async () => true),
|
|
2408
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
2409
|
+
isVerified: () => true,
|
|
2410
|
+
localVerified: true,
|
|
2411
|
+
crossSigningVerified: true,
|
|
2412
|
+
signedByOwner: true,
|
|
2413
|
+
})),
|
|
2414
|
+
getActiveSessionBackupVersion: vi.fn(async () => "7"),
|
|
2415
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
2416
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2417
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2418
|
+
auth_data: {},
|
|
2419
|
+
version: "7",
|
|
2420
|
+
})),
|
|
2421
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2422
|
+
trusted: true,
|
|
2423
|
+
matchesDecryptionKey: true,
|
|
2424
|
+
})),
|
|
2425
|
+
}));
|
|
2426
|
+
|
|
2427
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2428
|
+
encryption: true,
|
|
2429
|
+
});
|
|
2430
|
+
vi.spyOn(client, "getOwnCrossSigningPublicationStatus").mockResolvedValue({
|
|
2431
|
+
userId: "@bot:example.org",
|
|
2432
|
+
masterKeyPublished: true,
|
|
2433
|
+
selfSigningKeyPublished: true,
|
|
2434
|
+
userSigningKeyPublished: true,
|
|
2435
|
+
published: true,
|
|
2436
|
+
});
|
|
2437
|
+
let backupChecks = 0;
|
|
2438
|
+
vi.spyOn(client, "doRequest").mockImplementation(async (_method, endpoint) => {
|
|
2439
|
+
if (endpoint.includes("/room_keys/version")) {
|
|
2440
|
+
backupChecks += 1;
|
|
2441
|
+
return backupChecks >= 2 ? { version: "7" } : {};
|
|
2442
|
+
}
|
|
2443
|
+
return {};
|
|
2444
|
+
});
|
|
2445
|
+
|
|
2446
|
+
const result = await client.bootstrapOwnDeviceVerification();
|
|
2447
|
+
|
|
2448
|
+
expect(result.success).toBe(true);
|
|
2449
|
+
expect(result.verification.backupVersion).toBe("7");
|
|
2450
|
+
expect(bootstrapSecretStorage).toHaveBeenCalledWith(
|
|
2451
|
+
expect.objectContaining({ setupNewKeyBackup: true }),
|
|
2452
|
+
);
|
|
2453
|
+
});
|
|
2454
|
+
|
|
2455
|
+
it("does not recreate key backup during bootstrap when one already exists", async () => {
|
|
2456
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
2457
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
2458
|
+
const bootstrapSecretStorage = vi.fn(async () => {});
|
|
2459
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2460
|
+
on: vi.fn(),
|
|
2461
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
2462
|
+
bootstrapSecretStorage,
|
|
2463
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
2464
|
+
isCrossSigningReady: vi.fn(async () => true),
|
|
2465
|
+
userHasCrossSigningKeys: vi.fn(async () => true),
|
|
2466
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
2467
|
+
isVerified: () => true,
|
|
2468
|
+
localVerified: true,
|
|
2469
|
+
crossSigningVerified: true,
|
|
2470
|
+
signedByOwner: true,
|
|
2471
|
+
})),
|
|
2472
|
+
getActiveSessionBackupVersion: vi.fn(async () => "9"),
|
|
2473
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
2474
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2475
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2476
|
+
auth_data: {},
|
|
2477
|
+
version: "9",
|
|
2478
|
+
})),
|
|
2479
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2480
|
+
trusted: true,
|
|
2481
|
+
matchesDecryptionKey: true,
|
|
2482
|
+
})),
|
|
2483
|
+
}));
|
|
2484
|
+
|
|
2485
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2486
|
+
encryption: true,
|
|
2487
|
+
});
|
|
2488
|
+
vi.spyOn(client, "getOwnCrossSigningPublicationStatus").mockResolvedValue({
|
|
2489
|
+
userId: "@bot:example.org",
|
|
2490
|
+
masterKeyPublished: true,
|
|
2491
|
+
selfSigningKeyPublished: true,
|
|
2492
|
+
userSigningKeyPublished: true,
|
|
2493
|
+
published: true,
|
|
2494
|
+
});
|
|
2495
|
+
vi.spyOn(client, "doRequest").mockImplementation(async (_method, endpoint) => {
|
|
2496
|
+
if (endpoint.includes("/room_keys/version")) {
|
|
2497
|
+
return { version: "9" };
|
|
2498
|
+
}
|
|
2499
|
+
return {};
|
|
2500
|
+
});
|
|
2501
|
+
|
|
2502
|
+
const result = await client.bootstrapOwnDeviceVerification();
|
|
2503
|
+
|
|
2504
|
+
expect(result.success).toBe(true);
|
|
2505
|
+
expect(result.verification.backupVersion).toBe("9");
|
|
2506
|
+
const bootstrapSecretStorageCalls = bootstrapSecretStorage.mock.calls as Array<unknown[]>;
|
|
2507
|
+
expect(
|
|
2508
|
+
bootstrapSecretStorageCalls.some((call) =>
|
|
2509
|
+
Boolean((call[0] as { setupNewKeyBackup?: boolean })?.setupNewKeyBackup),
|
|
2510
|
+
),
|
|
2511
|
+
).toBe(false);
|
|
2512
|
+
});
|
|
2513
|
+
|
|
2514
|
+
it("does not report bootstrap errors when final verification state is healthy", async () => {
|
|
2515
|
+
const encoded = encodeRecoveryKey(new Uint8Array(Array.from({ length: 32 }, (_, i) => i + 90)));
|
|
2516
|
+
matrixJsClient.getUserId = vi.fn(() => "@bot:example.org");
|
|
2517
|
+
matrixJsClient.getDeviceId = vi.fn(() => "DEVICE123");
|
|
2518
|
+
matrixJsClient.getCrypto = vi.fn(() => ({
|
|
2519
|
+
on: vi.fn(),
|
|
2520
|
+
bootstrapCrossSigning: vi.fn(async () => {}),
|
|
2521
|
+
bootstrapSecretStorage: vi.fn(async () => {}),
|
|
2522
|
+
requestOwnUserVerification: vi.fn(async () => null),
|
|
2523
|
+
isCrossSigningReady: vi.fn(async () => true),
|
|
2524
|
+
userHasCrossSigningKeys: vi.fn(async () => true),
|
|
2525
|
+
getSecretStorageStatus: vi.fn(async () => ({
|
|
2526
|
+
ready: true,
|
|
2527
|
+
defaultKeyId: "SSSSKEY",
|
|
2528
|
+
secretStorageKeyValidityMap: { SSSSKEY: true },
|
|
2529
|
+
})),
|
|
2530
|
+
getDeviceVerificationStatus: vi.fn(async () => ({
|
|
2531
|
+
isVerified: () => true,
|
|
2532
|
+
localVerified: true,
|
|
2533
|
+
crossSigningVerified: true,
|
|
2534
|
+
signedByOwner: true,
|
|
2535
|
+
})),
|
|
2536
|
+
getActiveSessionBackupVersion: vi.fn(async () => "12"),
|
|
2537
|
+
getSessionBackupPrivateKey: vi.fn(async () => new Uint8Array([1])),
|
|
2538
|
+
getKeyBackupInfo: vi.fn(async () => ({
|
|
2539
|
+
algorithm: "m.megolm_backup.v1.curve25519-aes-sha2",
|
|
2540
|
+
auth_data: {},
|
|
2541
|
+
version: "12",
|
|
2542
|
+
})),
|
|
2543
|
+
isKeyBackupTrusted: vi.fn(async () => ({
|
|
2544
|
+
trusted: true,
|
|
2545
|
+
matchesDecryptionKey: true,
|
|
2546
|
+
})),
|
|
2547
|
+
}));
|
|
2548
|
+
|
|
2549
|
+
const client = new MatrixClient("https://matrix.example.org", "token", {
|
|
2550
|
+
encryption: true,
|
|
2551
|
+
});
|
|
2552
|
+
vi.spyOn(client, "getOwnCrossSigningPublicationStatus").mockResolvedValue({
|
|
2553
|
+
userId: "@bot:example.org",
|
|
2554
|
+
masterKeyPublished: true,
|
|
2555
|
+
selfSigningKeyPublished: true,
|
|
2556
|
+
userSigningKeyPublished: true,
|
|
2557
|
+
published: true,
|
|
2558
|
+
});
|
|
2559
|
+
vi.spyOn(client, "doRequest").mockResolvedValue({ version: "12" });
|
|
2560
|
+
|
|
2561
|
+
const result = await client.bootstrapOwnDeviceVerification({
|
|
2562
|
+
recoveryKey: encoded as string,
|
|
2563
|
+
});
|
|
2564
|
+
|
|
2565
|
+
expect(result.success).toBe(true);
|
|
2566
|
+
expect(result.error).toBeUndefined();
|
|
2567
|
+
});
|
|
2568
|
+
});
|