1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
|
<?php
namespace App\Controllers\Client;
use App\Database;
use App\Errors\AppException;
use App\Errors\UnknownError;
use App\Models\Device;
use App\Models\RoomEvent;
use App\Models\Tokens;
use App\Models\User;
use App\Support\Logger;
use App\Support\Parser;
use App\Support\RequestValidator;
use Matrix\Data\AccountData;
use Matrix\Data\DeviceLists;
use Matrix\Data\LoginFlow;
use Matrix\Data\Presence;
use Matrix\Data\Room\Ephemeral;
use Matrix\Data\Room\JoinedRoom;
use Matrix\Data\Room\RoomSummary;
use Matrix\Data\Room\Rooms;
use Matrix\Data\Room\State;
use Matrix\Data\Room\Timeline;
use Matrix\Data\Room\UnreadNotificationCounts;
use Matrix\Data\ToDevice;
use Matrix\Enums\ErrorCode;
use Matrix\Enums\LoginType;
use Matrix\Enums\MembershipState;
use Matrix\Enums\PresenceState;
use Matrix\Enums\UserRegistrationKind;
use Matrix\Events\PresenceEvent;
use Matrix\Responses\ClientLoginGetResponse;
use Matrix\Responses\ClientLoginPostResponse;
use Matrix\Responses\ClientRefreshPostResponse;
use Matrix\Responses\ClientRegisterPostResponse;
use Matrix\Responses\ClientSyncGetResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
class ClientController
{
#[Route(path: "_matrix/client/r0/login", methods: ["GET"])]
#[Route(path: "_matrix/client/v3/login", methods: ["GET"])]
public function supportedLoginTypes(Request $request): Response
{
return new JsonResponse(new ClientLoginGetResponse([
(new LoginFlow(LoginType::PASSWORD)),
]));
}
#[Route(path: "_matrix/client/r0/login", methods: ["POST"])]
#[Route(path: "_matrix/client/v3/login", methods: ["POST"])]
public function login(Request $request): Response
{
Logger::logRequestToFile($request);
$body = json_decode($request->getContent(), true);
RequestValidator::validateJson();
// validate login type
$loginType = null;
try {
$loginType = LoginType::from($body["type"]);
} catch (\ValueError $error) {
throw new UnknownError("Bad login type.", Response::HTTP_BAD_REQUEST);
}
// get user id
$userId = Parser::parseUser($body["identifier"]["user"]);
if (empty($userId["server"])) {
$userId = "@$userId[username]:$_ENV[DOMAIN]";
#$userId = "@$userId[username]:localhost";
} else {
$userId = "@$userId[username]:$userId[server]";
}
if ($loginType !== LoginType::PASSWORD) {
throw new AppException(ErrorCode::UNRECOGNIZED, "only password login supported for now", Response::HTTP_SERVICE_UNAVAILABLE);
}
$user = User::fetchWithPassword($userId, $body["password"]);
if (! $user) {
throw new AppException(ErrorCode::FORBIDDEN, "Invalid credentials", Response::HTTP_FORBIDDEN);
}
$deviceId = $body["device_id"] ?? "";
$device = null;
$tokens = null;
// create new device with tokens
if (empty($deviceId)) {
$device = Device::new(
$user->getId(),
initialDisplayName: $body["initial_device_display_name"] ?? "",
);
$device->insert();
$tokens = Tokens::new($userId, $device->getId());
$tokens->insert();
} else { // fetch existing device and tokens
$device = $user->fetchDevice($deviceId);
$tokens = Tokens::fetch($userId, $device->getId());
if (empty($tokens)) {
throw new AppException(
ErrorCode::UNKNOWN_TOKEN,
"Soft logged out",
Response::HTTP_UNAUTHORIZED,
["soft_logout" => true],
);
}
}
return new JsonResponse(new ClientLoginPostResponse(
accessToken: $tokens->getAccessToken(),
deviceId:$device->getId(),
userId: $user->getId(),
expiresInMilliseconds: $tokens->getExpiresIn(),
refreshToken: $tokens->getRefreshToken(),
));
}
#[Route(path: "_matrix/client/v3/register", methods: ["POST"])]
public function register(Request $request): Response
{
$body = json_decode($request->getContent(), true);
RequestValidator::validateJson();
// validate kind
$kind = null;
try {
$kind = UserRegistrationKind::from($request->query->get("kind") ?? "user");
} catch (\ValueError $error) {
throw new UnknownError("Bad registration kind.", Response::HTTP_BAD_REQUEST);
}
$username = $body["username"];
$userId = "@$username:$_ENV[DOMAIN]";
Database::getInstance()->query("insert into users (id, password) values (:id, :password)", [
"id" => $userId,
"password" => $body["password"],
]);
$device_id = $body["device_id"] ?? "";
$initialDeviceDisplayName = $body["initial_device_display_name"] ?? "";
$device = Device::new($userId, $device_id, $initialDeviceDisplayName);
$device->insert();
$tokens = Tokens::new($userId, $device->getId());
$tokens->insert();
return new JsonResponse(new ClientRegisterPostResponse(
accessToken: $tokens->getAccessToken(),
deviceId: $device->getId(),
expiresInMilliseconds: $tokens->getExpiresIn(),
refreshToken: $tokens->getRefreshToken(),
userId: $userId,
));
}
/**
* @see https://spec.matrix.org/v1.15/client-server-api/#get_matrixclientv3sync
* @see https://spec.matrix.org/v1.15/client-server-api/#extensions-to-sync
*/
#[Route(path: "_matrix/client/r0/sync", methods: ["GET"])]
#[Route(path: "_matrix/client/v3/sync", methods: ["GET"])]
public function sync(Request $request): Response
{
$user = User::authenticateWithRequest($request);
$filter = $request->query->get("filter", "");
$syncFullState = $request->query->get("full_state", false);
$setPresence = PresenceState::tryFrom($request->query->get("set_presence") ?? "") ?? PresenceState::ONLINE;
$since = $request->query->get("since", "");
$timeout = $request->query->get("timeout", 0);
$useStateAfter = $request->query->get("use_state_after", false);
if (! empty($filter)) {
if (str_starts_with($filter, "{")) {
$filter = json_decode($filter, true);
} else {
$filter = Database::getInstance()->query("select * from filters where id=:id", ["id" => $filter])->fetch();
}
}
$rooms = Database::getInstance()->query(<<<SQL
select * from rooms
left join room_memberships
on rooms.id = room_memberships.room_id
where room_memberships.user_id = :user_id
SQL, [
"user_id" => $user->getId(),
])->fetchAll();
$invitedRooms = [];
$joinedRooms = [];
$knockedRooms = [];
$leftRooms = [];
foreach ($rooms as $room) {
$events = Database::getInstance()->query(<<<SQL
select * from room_events
where room_id = :room_id
SQL, [
"room_id" => $room["room_id"],
#"limit" => ($filter["room"]["timeline"]["limit"] ?? false) ? "limit " . $filter["room"]["timeline"]["limit"] : "",
])->fetchAll();
if ($since === "" && MembershipState::tryFrom($room["state"]) === MembershipState::JOIN) {
$joinedRooms[$room["room_id"]] = new JoinedRoom(
accountData: new AccountData([]),
ephemeral: new Ephemeral([]),
state: new State([]),
summary: new RoomSummary(
heroes: [],
invitedMemberCount: 0,
joinedMemberCount: 1,
),
timeline: new Timeline(
events: array_map([RoomEvent::class, "transformEvent"], $events),
limited: false,# $filter["room"]["timeline"]["limit"] ?? false,
previousBatch: null,
),
unreadNotifications: new UnreadNotificationCounts(0, 0),
unreadThreadNotifications: [],
);
}
}
return new JsonResponse(new ClientSyncGetResponse(
nextBatch: "1",
accountData: new AccountData([]),
deviceLists: new DeviceLists([], []),
deviceOneTimeKeysCount: [
"signed_curve25519" => 10,
],
presence: new Presence([
new PresenceEvent(
sender: $user->getId(),
presence: $setPresence,
),
]),
rooms: new Rooms(
$invitedRooms,
$joinedRooms,
$knockedRooms,
$leftRooms,
),
toDevice: new ToDevice([]),
));
}
#[Route(path: "/_matrix/client/v3/refresh", methods: ["POST"])]
public function refresh(Request $request): Response
{
$body = json_decode($request->getContent(), true);
RequestValidator::validateJson();
$tokens = Tokens::fetchWithRefreshToken($body["refresh_token"]);
if (empty($tokens)) {
throw new AppException(
ErrorCode::UNKNOWN_TOKEN,
"Soft logged out",
Response::HTTP_UNAUTHORIZED,
["soft_logout" => true],
);
}
$newTokens = Tokens::new($tokens->getUserId(), $tokens->getDeviceId());
$newTokens->insert();
return new JsonResponse(new ClientRefreshPostResponse(
accessToken: $newTokens->getAccessToken(),
expiresInMilliseconds: $newTokens->getExpiresIn(),
refreshToken: $newTokens->getRefreshToken(),
));
}
}
|