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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
|
import { deepStrictEqual, strictEqual } from 'assert';
import { readFile } from 'fs/promises';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import * as Misskey from 'misskey-js';
import { WebSocket } from 'ws';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export const ADMIN_PARAMS = { username: 'admin', password: 'admin' };
const ADMIN_CACHE = new Map<Host, SigninResponse>();
await Promise.all([
fetchAdmin('a.test'),
fetchAdmin('b.test'),
]);
type SigninResponse = Omit<Misskey.entities.SigninFlowResponse & { finished: true }, 'finished'>;
export type LoginUser = SigninResponse & {
client: Misskey.api.APIClient;
username: string;
password: string;
};
/** used for avoiding overload and some endpoints */
export type Request = <
E extends keyof Misskey.Endpoints,
P extends Misskey.Endpoints[E]['req'],
>(
endpoint: E,
params: P,
credential?: string | null,
) => Promise<Misskey.api.SwitchCaseResponseType<E, P>>;
type Host = 'a.test' | 'b.test';
export async function sleep(ms = 250): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function signin(
host: Host,
params: Misskey.entities.SigninFlowRequest,
): Promise<SigninResponse> {
// wait for a second to prevent hit rate limit
await sleep(1000);
return await (new Misskey.api.APIClient({ origin: `https://${host}` }).request as Request)('signin-flow', params)
.then(res => {
strictEqual(res.finished, true);
if (params.username === ADMIN_PARAMS.username) ADMIN_CACHE.set(host, res);
return res;
})
.then(({ id, i }) => ({ id, i }))
.catch(async err => {
if (err.code === 'TOO_MANY_AUTHENTICATION_FAILURES') {
await sleep(Math.random() * 2000);
return await signin(host, params);
}
throw err;
});
}
async function createAdmin(host: Host): Promise<Misskey.entities.SignupResponse | undefined> {
const client = new Misskey.api.APIClient({ origin: `https://${host}` });
return await client.request('admin/accounts/create', ADMIN_PARAMS).then(res => {
ADMIN_CACHE.set(host, {
id: res.id,
// @ts-expect-error FIXME: openapi-typescript generates incorrect response type for this endpoint, so ignore this
i: res.token,
});
return res as Misskey.entities.SignupResponse;
}).then(async res => {
await client.request('admin/roles/update-default-policies', {
policies: {
/** TODO: @see https://github.com/misskey-dev/misskey/issues/14169 */
rateLimitFactor: 0 as never,
},
}, res.token);
return res;
}).catch(err => {
if (err.info.e.message === 'access denied') return undefined;
throw err;
});
}
export async function fetchAdmin(host: Host): Promise<LoginUser> {
const admin = ADMIN_CACHE.get(host) ?? await signin(host, ADMIN_PARAMS)
.catch(async err => {
if (err.id === '6cc579cc-885d-43d8-95c2-b8c7fc963280') {
await createAdmin(host);
return await signin(host, ADMIN_PARAMS);
}
throw err;
});
return {
...admin,
client: new Misskey.api.APIClient({ origin: `https://${host}`, credential: admin.i }),
...ADMIN_PARAMS,
};
}
export async function createAccount(host: Host): Promise<LoginUser> {
const username = crypto.randomUUID().replaceAll('-', '').substring(0, 20);
const password = crypto.randomUUID().replaceAll('-', '');
const admin = await fetchAdmin(host);
await admin.client.request('admin/accounts/create', { username, password });
const signinRes = await signin(host, { username, password });
return {
...signinRes,
client: new Misskey.api.APIClient({ origin: `https://${host}`, credential: signinRes.i }),
username,
password,
};
}
export async function createModerator(host: Host): Promise<LoginUser> {
const user = await createAccount(host);
const role = await createRole(host, {
name: 'Moderator',
isModerator: true,
});
const admin = await fetchAdmin(host);
await admin.client.request('admin/roles/assign', { roleId: role.id, userId: user.id });
return user;
}
export async function createRole(
host: Host,
params: Partial<Misskey.entities.AdminRolesCreateRequest> = {},
): Promise<Misskey.entities.Role> {
const admin = await fetchAdmin(host);
return await admin.client.request('admin/roles/create', {
name: 'Some role',
description: 'Role for testing',
color: null,
iconUrl: null,
target: 'conditional',
condFormula: {},
isPublic: true,
isModerator: false,
isAdministrator: false,
isExplorable: true,
asBadge: false,
canEditMembersByModerator: false,
displayOrder: 0,
policies: {},
...params,
});
}
export async function resolveRemoteUser(
host: Host,
id: string,
from: LoginUser,
): Promise<Misskey.entities.UserDetailedNotMe> {
const uri = `https://${host}/users/${id}`;
return await from.client.request('ap/show', { uri })
.then(res => {
strictEqual(res.type, 'User');
strictEqual(res.object.uri, uri);
return res.object;
});
}
export async function resolveRemoteNote(
host: Host,
id: string,
from: LoginUser,
): Promise<Misskey.entities.Note> {
const uri = `https://${host}/notes/${id}`;
return await from.client.request('ap/show', { uri })
.then(res => {
strictEqual(res.type, 'Note');
strictEqual(res.object.uri, uri);
return res.object;
});
}
export async function uploadFile(
host: Host,
user: { i: string },
path = '../../test/resources/192.jpg',
): Promise<Misskey.entities.DriveFile> {
const filename = path.split('/').pop() ?? 'untitled';
const blob = new Blob([await readFile(join(__dirname, path))]);
const body = new FormData();
body.append('i', user.i);
body.append('force', 'true');
body.append('file', blob);
body.append('name', filename);
return await fetch(`https://${host}/api/drive/files/create`, { method: 'POST', body })
.then(async res => await res.json());
}
export async function addCustomEmoji(
host: Host,
param?: Partial<Misskey.entities.AdminEmojiAddRequest>,
path?: string,
): Promise<Misskey.entities.EmojiDetailed> {
const admin = await fetchAdmin(host);
const name = crypto.randomUUID().replaceAll('-', '');
const file = await uploadFile(host, admin, path);
return await admin.client.request('admin/emoji/add', { name, fileId: file.id, ...param });
}
export function deepStrictEqualWithExcludedFields<T>(actual: T, expected: T, excludedFields: (keyof T)[]) {
const _actual = structuredClone(actual);
const _expected = structuredClone(expected);
for (const obj of [_actual, _expected]) {
for (const field of excludedFields) {
delete obj[field];
}
}
deepStrictEqual(_actual, _expected);
}
export async function isFired<C extends keyof Misskey.Channels, T extends keyof Misskey.Channels[C]['events']>(
host: Host,
user: { i: string },
channel: C,
trigger: () => Promise<unknown>,
type: T,
// @ts-expect-error TODO: why getting error here?
cond: (msg: Parameters<Misskey.Channels[C]['events'][T]>[0]) => boolean,
params?: Misskey.Channels[C]['params'],
): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
const stream = new Misskey.Stream(`wss://${host}`, { token: user.i }, { WebSocket });
const connection = stream.useChannel(channel, params);
connection.on(type as any, ((msg: any) => {
if (cond(msg)) {
stream.close();
clearTimeout(timer);
resolve(true);
}
}) as any);
let timer: NodeJS.Timeout | undefined;
await trigger().then(() => {
timer = setTimeout(() => {
stream.close();
resolve(false);
}, 500);
}).catch(err => {
stream.close();
clearTimeout(timer);
reject(err);
});
});
}
export async function isNoteUpdatedEventFired(
host: Host,
user: { i: string },
noteId: string,
trigger: () => Promise<unknown>,
cond: (msg: Parameters<Misskey.StreamEvents['noteUpdated']>[0]) => boolean,
): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
const stream = new Misskey.Stream(`wss://${host}`, { token: user.i }, { WebSocket });
stream.send('s', { id: noteId });
stream.on('noteUpdated', msg => {
if (cond(msg)) {
stream.close();
clearTimeout(timer);
resolve(true);
}
});
let timer: NodeJS.Timeout | undefined;
await trigger().then(() => {
timer = setTimeout(() => {
stream.close();
resolve(false);
}, 500);
}).catch(err => {
stream.close();
clearTimeout(timer);
reject(err);
});
});
}
export async function assertNotificationReceived(
receiverHost: Host,
receiver: LoginUser,
trigger: () => Promise<unknown>,
cond: (notification: Misskey.entities.Notification) => boolean,
expect: boolean,
) {
const streamingFired = await isFired(receiverHost, receiver, 'main', trigger, 'notification', cond);
strictEqual(streamingFired, expect);
const endpointFired = await receiver.client.request('i/notifications', {})
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
.then(([notification]) => notification != null ? cond(notification) : false);
strictEqual(endpointFired, expect);
}
|