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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
|
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { Inject, Injectable } from '@nestjs/common';
import * as argon2 from 'argon2';
import { IsNull } from 'typeorm';
import { DI } from '@/di-symbols.js';
import type { RegistrationTicketsRepository, UsedUsernamesRepository, UserPendingsRepository, UserProfilesRepository, UsersRepository, MiRegistrationTicket, MiMeta } from '@/models/_.js';
import type { Config } from '@/config.js';
import { CaptchaService } from '@/core/CaptchaService.js';
import { IdService } from '@/core/IdService.js';
import { SignupService } from '@/core/SignupService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { EmailService } from '@/core/EmailService.js';
import { MiLocalUser } from '@/models/User.js';
import { FastifyReplyError } from '@/misc/fastify-reply-error.js';
import { bindThis } from '@/decorators.js';
import { L_CHARS, secureRndstr } from '@/misc/secure-rndstr.js';
import { RoleService } from '@/core/RoleService.js';
import { SigninService } from './SigninService.js';
import type { FastifyRequest, FastifyReply } from 'fastify';
@Injectable()
export class SignupApiService {
constructor(
@Inject(DI.config)
private config: Config,
@Inject(DI.meta)
private meta: MiMeta,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@Inject(DI.userProfilesRepository)
private userProfilesRepository: UserProfilesRepository,
@Inject(DI.userPendingsRepository)
private userPendingsRepository: UserPendingsRepository,
@Inject(DI.usedUsernamesRepository)
private usedUsernamesRepository: UsedUsernamesRepository,
@Inject(DI.registrationTicketsRepository)
private registrationTicketsRepository: RegistrationTicketsRepository,
private userEntityService: UserEntityService,
private idService: IdService,
private captchaService: CaptchaService,
private signupService: SignupService,
private signinService: SigninService,
private emailService: EmailService,
private roleService: RoleService,
) {
}
@bindThis
public async signup(
request: FastifyRequest<{
Body: {
username: string;
password: string;
host?: string;
invitationCode?: string;
emailAddress?: string;
reason?: string;
'hcaptcha-response'?: string;
'g-recaptcha-response'?: string;
'turnstile-response'?: string;
'm-captcha-response'?: string;
'frc-captcha-solution'?: string;
'testcaptcha-response'?: string;
}
}>,
reply: FastifyReply,
) {
const body = request.body;
// Verify *Captcha
// ただしテスト時はこの機構は障害となるため無効にする
if (process.env.NODE_ENV !== 'test') {
if (this.meta.enableHcaptcha && this.meta.hcaptchaSecretKey) {
await this.captchaService.verifyHcaptcha(this.meta.hcaptchaSecretKey, body['hcaptcha-response']).catch(err => {
throw new FastifyReplyError(400, err);
});
}
if (this.meta.enableMcaptcha && this.meta.mcaptchaSecretKey && this.meta.mcaptchaSitekey && this.meta.mcaptchaInstanceUrl) {
await this.captchaService.verifyMcaptcha(this.meta.mcaptchaSecretKey, this.meta.mcaptchaSitekey, this.meta.mcaptchaInstanceUrl, body['m-captcha-response']).catch(err => {
throw new FastifyReplyError(400, err);
});
}
if (this.meta.enableRecaptcha && this.meta.recaptchaSecretKey) {
await this.captchaService.verifyRecaptcha(this.meta.recaptchaSecretKey, body['g-recaptcha-response']).catch(err => {
throw new FastifyReplyError(400, err);
});
}
if (this.meta.enableTurnstile && this.meta.turnstileSecretKey) {
await this.captchaService.verifyTurnstile(this.meta.turnstileSecretKey, body['turnstile-response']).catch(err => {
throw new FastifyReplyError(400, err);
});
}
if (this.meta.enableFC && this.meta.fcSecretKey) {
await this.captchaService.verifyFriendlyCaptcha(this.meta.fcSecretKey, body['frc-captcha-solution']).catch(err => {
throw new FastifyReplyError(400, err);
});
}
if (this.meta.enableTestcaptcha) {
await this.captchaService.verifyTestcaptcha(body['testcaptcha-response']).catch(err => {
throw new FastifyReplyError(400, err);
});
}
}
const username = body['username'];
const password = body['password'];
const host: string | null = process.env.NODE_ENV === 'test' ? (body['host'] ?? null) : null;
const invitationCode = body['invitationCode'];
const reason = body['reason'];
const emailAddress = body['emailAddress'];
if (this.meta.emailRequiredForSignup) {
if (emailAddress == null || typeof emailAddress !== 'string') {
reply.code(400);
return;
}
const res = await this.emailService.validateEmailForAccount(emailAddress);
if (!res.available) {
reply.code(400);
return;
}
}
if (this.meta.approvalRequiredForSignup) {
if (reason == null || typeof reason !== 'string') {
reply.code(400);
return;
}
}
let ticket: MiRegistrationTicket | null = null;
if (this.meta.disableRegistration) {
if (invitationCode == null || typeof invitationCode !== 'string') {
reply.code(400);
return;
}
ticket = await this.registrationTicketsRepository.findOneBy({
code: invitationCode,
});
if (ticket == null || ticket.usedById != null) {
reply.code(400);
return;
}
if (ticket.expiresAt && ticket.expiresAt < new Date()) {
reply.code(400);
return;
}
// メアド認証が有効の場合
if (this.meta.emailRequiredForSignup) {
// メアド認証済みならエラー
if (ticket.usedBy) {
reply.code(400);
return;
}
// 認証しておらず、メール送信から30分以内ならエラー
if (ticket.usedAt && ticket.usedAt.getTime() + (1000 * 60 * 30) > Date.now()) {
reply.code(400);
return;
}
} else if (ticket.usedAt) {
reply.code(400);
return;
}
}
if (this.meta.emailRequiredForSignup) {
if (await this.usersRepository.exists({ where: { usernameLower: username.toLowerCase(), host: IsNull() } })) {
throw new FastifyReplyError(400, 'DUPLICATED_USERNAME');
}
// Check deleted username duplication
if (await this.usedUsernamesRepository.exists({ where: { username: username.toLowerCase() } })) {
throw new FastifyReplyError(400, 'USED_USERNAME');
}
const isPreserved = this.meta.preservedUsernames.map(x => x.toLowerCase()).includes(username.toLowerCase());
if (isPreserved) {
throw new FastifyReplyError(400, 'DENIED_USERNAME');
}
const code = secureRndstr(16, { chars: L_CHARS });
// Generate hash of password
const hash = await argon2.hash(password);
const pendingUser = await this.userPendingsRepository.insertOne({
id: this.idService.gen(),
code,
email: emailAddress!,
username: username,
password: hash,
reason: reason,
});
const link = `${this.config.url}/signup-complete/${code}`;
this.emailService.sendEmail(emailAddress!, 'Signup',
`To complete signup, please click this link:<br><a href="${link}">${link}</a>`,
`To complete signup, please click this link: ${link}`);
if (ticket) {
await this.registrationTicketsRepository.update(ticket.id, {
usedAt: new Date(),
pendingUserId: pendingUser.id,
});
}
reply.code(204);
return;
} else if (this.meta.approvalRequiredForSignup) {
const { account } = await this.signupService.signup({
username, password, host, reason,
});
if (emailAddress) {
this.emailService.sendEmail(emailAddress, 'Approval pending',
'Congratulations! Your account is now pending approval. You will get notified when you have been accepted.',
'Congratulations! Your account is now pending approval. You will get notified when you have been accepted.');
}
if (ticket) {
await this.registrationTicketsRepository.update(ticket.id, {
usedAt: new Date(),
usedBy: account,
usedById: account.id,
});
}
const moderators = await this.roleService.getModerators();
for (const moderator of moderators) {
const profile = await this.userProfilesRepository.findOneBy({ userId: moderator.id });
if (profile?.email) {
this.emailService.sendEmail(profile.email, 'New user awaiting approval',
`A new user called ${account.username} is awaiting approval with the following reason: "${reason}"`,
`A new user called ${account.username} is awaiting approval with the following reason: "${reason}"`);
}
}
reply.code(204);
return;
} else {
try {
const { account, secret } = await this.signupService.signup({
username, password, host,
});
const res = await this.userEntityService.pack(account, account, {
schema: 'MeDetailed',
includeSecrets: true,
});
if (ticket) {
await this.registrationTicketsRepository.update(ticket.id, {
usedAt: new Date(),
usedBy: account,
usedById: account.id,
});
}
return {
...res,
token: secret,
};
} catch (err) {
throw new FastifyReplyError(400, typeof err === 'string' ? err : (err as Error).toString());
}
}
}
@bindThis
public async signupPending(request: FastifyRequest<{ Body: { code: string; } }>, reply: FastifyReply) {
const body = request.body;
const code = body['code'];
try {
const pendingUser = await this.userPendingsRepository.findOneByOrFail({ code });
if (this.idService.parse(pendingUser.id).date.getTime() + (1000 * 60 * 30) < Date.now()) {
throw new FastifyReplyError(400, 'EXPIRED');
}
const { account, secret } = await this.signupService.signup({
username: pendingUser.username,
passwordHash: pendingUser.password,
reason: pendingUser.reason,
});
this.userPendingsRepository.delete({
id: pendingUser.id,
});
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: account.id });
await this.userProfilesRepository.update({ userId: profile.userId }, {
email: pendingUser.email,
emailVerified: true,
emailVerifyCode: null,
});
const ticket = await this.registrationTicketsRepository.findOneBy({ pendingUserId: pendingUser.id });
if (ticket) {
await this.registrationTicketsRepository.update(ticket.id, {
usedBy: account,
usedById: account.id,
pendingUserId: null,
});
}
if (this.meta.approvalRequiredForSignup) {
if (pendingUser.email) {
this.emailService.sendEmail(pendingUser.email, 'Approval pending',
'Congratulations! Your account is now pending approval. You will get notified when you have been accepted.',
'Congratulations! Your account is now pending approval. You will get notified when you have been accepted.');
}
const moderators = await this.roleService.getModerators();
for (const moderator of moderators) {
const profile = await this.userProfilesRepository.findOneBy({ userId: moderator.id });
if (profile?.email) {
this.emailService.sendEmail(profile.email, 'New user awaiting approval',
`A new user called ${pendingUser.username} is awaiting approval with the following reason: "${pendingUser.reason}"`,
`A new user called ${pendingUser.username} is awaiting approval with the following reason: "${pendingUser.reason}"`);
}
}
return { pendingApproval: true };
}
return this.signinService.signin(request, reply, account as MiLocalUser);
} catch (err) {
throw new FastifyReplyError(400, typeof err === 'string' ? err : (err as Error).toString());
}
}
}
|