Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature] 2FAリカバリコードの実装 #10972

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions locales/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1776,6 +1776,11 @@ export interface Locale {
"renewTOTPConfirm": string;
"renewTOTPOk": string;
"renewTOTPCancel": string;
"generateRecoveryCode": string;
"generateRecoveryCodeConfirm": string;
"generateRecoveryCodeOK": string;
"generateRecoveryCodeCancel": string;
"recoveryCodeInfo": string;
};
"_permissions": {
"read:account": string;
Expand Down
5 changes: 5 additions & 0 deletions locales/ja-JP.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1694,6 +1694,11 @@ _2fa:
renewTOTPConfirm: "今までの認証アプリの確認コードは使用できなくなります"
renewTOTPOk: "再設定する"
renewTOTPCancel: "やめておく"
generateRecoveryCode: "リカバリーコードを発行"
generateRecoveryCodeConfirm: "すでに発行されているリカバリーコードは使用できなくなります"
generateRecoveryCodeOK: "発行する"
generateRecoveryCodeCancel: "やめておく"
recoveryCodeInfo: "これらのリカバリーコードを安全な場所にメモしてください。\nメモし忘れた場合再生成する必要があります。\n各リカバリーコードは1回のみ使用可能です。"

_permissions:
"read:account": "アカウントの情報を見る"
Expand Down
11 changes: 11 additions & 0 deletions packages/backend/migration/1686242300149-TwoFactorRecoveryCode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export class TwoFactorRecoveryCode1686242300149 {
name = 'TwoFactorRecoveryCode1686242300149'

async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "user_profile" ADD "twoFactorRecoveryCodes" text NOT NULL DEFAULT '[]'`);
}

async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "user_profile" DROP COLUMN "twoFactorRecoveryCodes"`);
}
}
5 changes: 5 additions & 0 deletions packages/backend/src/models/entities/UserProfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ export class UserProfile {
})
public twoFactorEnabled: boolean;

@Column('simple-array', {
default: [],
})
public twoFactorRecoveryCodes: string[];

@Column('boolean', {
default: false,
})
Expand Down
4 changes: 4 additions & 0 deletions packages/backend/src/server/api/EndpointsModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ import * as ep___i_2fa_keyDone from './endpoints/i/2fa/key-done.js';
import * as ep___i_2fa_passwordLess from './endpoints/i/2fa/password-less.js';
import * as ep___i_2fa_registerKey from './endpoints/i/2fa/register-key.js';
import * as ep___i_2fa_register from './endpoints/i/2fa/register.js';
import * as ep___i_2fa_generateRecoveryCodes from './endpoints/i/2fa/generate-recovery-codes.js';
import * as ep___i_2fa_updateKey from './endpoints/i/2fa/update-key.js';
import * as ep___i_2fa_removeKey from './endpoints/i/2fa/remove-key.js';
import * as ep___i_2fa_unregister from './endpoints/i/2fa/unregister.js';
Expand Down Expand Up @@ -521,6 +522,7 @@ const $i_2fa_keyDone: Provider = { provide: 'ep:i/2fa/key-done', useClass: ep___
const $i_2fa_passwordLess: Provider = { provide: 'ep:i/2fa/password-less', useClass: ep___i_2fa_passwordLess.default };
const $i_2fa_registerKey: Provider = { provide: 'ep:i/2fa/register-key', useClass: ep___i_2fa_registerKey.default };
const $i_2fa_register: Provider = { provide: 'ep:i/2fa/register', useClass: ep___i_2fa_register.default };
const $i_2fa_generateRecoveryCodes: Provider = { provide: 'ep:i/2fa/generate-recovery-codes', useClass: ep___i_2fa_generateRecoveryCodes.default };
const $i_2fa_updateKey: Provider = { provide: 'ep:i/2fa/update-key', useClass: ep___i_2fa_updateKey.default };
const $i_2fa_removeKey: Provider = { provide: 'ep:i/2fa/remove-key', useClass: ep___i_2fa_removeKey.default };
const $i_2fa_unregister: Provider = { provide: 'ep:i/2fa/unregister', useClass: ep___i_2fa_unregister.default };
Expand Down Expand Up @@ -866,6 +868,7 @@ const $retention: Provider = { provide: 'ep:retention', useClass: ep___retention
$i_2fa_passwordLess,
$i_2fa_registerKey,
$i_2fa_register,
$i_2fa_generateRecoveryCodes,
$i_2fa_updateKey,
$i_2fa_removeKey,
$i_2fa_unregister,
Expand Down Expand Up @@ -1205,6 +1208,7 @@ const $retention: Provider = { provide: 'ep:retention', useClass: ep___retention
$i_2fa_passwordLess,
$i_2fa_registerKey,
$i_2fa_register,
$i_2fa_generateRecoveryCodes,
$i_2fa_updateKey,
$i_2fa_removeKey,
$i_2fa_unregister,
Expand Down
2 changes: 2 additions & 0 deletions packages/backend/src/server/api/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ import * as ep___i_2fa_keyDone from './endpoints/i/2fa/key-done.js';
import * as ep___i_2fa_passwordLess from './endpoints/i/2fa/password-less.js';
import * as ep___i_2fa_registerKey from './endpoints/i/2fa/register-key.js';
import * as ep___i_2fa_register from './endpoints/i/2fa/register.js';
import * as ep___i_2fa_generateRecoveryCodes from './endpoints/i/2fa/generate-recovery-codes.js';
import * as ep___i_2fa_updateKey from './endpoints/i/2fa/update-key.js';
import * as ep___i_2fa_removeKey from './endpoints/i/2fa/remove-key.js';
import * as ep___i_2fa_unregister from './endpoints/i/2fa/unregister.js';
Expand Down Expand Up @@ -519,6 +520,7 @@ const eps = [
['i/2fa/password-less', ep___i_2fa_passwordLess],
['i/2fa/register-key', ep___i_2fa_registerKey],
['i/2fa/register', ep___i_2fa_register],
['i/2fa/generate-recovery-codes', ep___i_2fa_generateRecoveryCodes],
['i/2fa/update-key', ep___i_2fa_updateKey],
['i/2fa/remove-key', ep___i_2fa_removeKey],
['i/2fa/unregister', ep___i_2fa_unregister],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import bcrypt from 'bcryptjs';
import rndstr from 'rndstr';
import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import type { UserProfilesRepository } from '@/models/index.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
import { DI } from '@/di-symbols.js';
import { ApiError } from '../../../error.js';

export const meta = {
requireCredential: true,

secure: true,

error: {
twoFactorNotSetup: {
message: '2fa is not set up.',
code: 'NOT_SET_UP',
id: '1f23a9d2-074c-4a57-23b7-eb538defa31f'
}
}
} as const;

export const paramDef = {
type: 'object',
properties: {
password: { type: 'string' },
},
required: ['password'],
} as const;

// eslint-disable-next-line import/no-default-export
@Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> {
constructor(
@Inject(DI.userProfilesRepository)
private userProfilesRepository: UserProfilesRepository,

private userEntityService: UserEntityService,
private globalEventService: GlobalEventService,
) {
super(meta, paramDef, async(ps, me) => {
const profile = await this.userProfilesRepository.findOneByOrFail({ userId: me.id });

// Compare password
const same = await bcrypt.compare(ps.password, profile.password!);

if (!same) {
throw new Error('incorrect password');
}

if (!profile.twoFactorEnabled) {
throw new ApiError(meta.error.twoFactorNotSetup);
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const recoveryCodes: string[] = [...Array(8).keys()].map(_ => rndstr({ length: 8 }));
await this.userProfilesRepository.update(me.id, {
twoFactorRecoveryCodes: recoveryCodes,
});
this.globalEventService.publishMainStream(me.id, 'meUpdated', await this.userEntityService.pack(me.id, me, {
detail: true,
includeSecrets: true,
}));

return recoveryCodes;
});
}
}
29 changes: 29 additions & 0 deletions packages/frontend/src/pages/settings/2fa.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
<MkInfo>{{ i18n.ts._2fa.whyTOTPOnlyRenew }}</MkInfo>
</template>
<MkButton v-else @click="unregisterTOTP">{{ i18n.ts.unregister }}</MkButton>
<MkButton @click="generateRecoveryCode">{{ i18n.ts._2fa.generateRecoveryCode }}</MkButton>
<div v-if="showRecoveryCode">
{{ i18n.ts._2fa.recoveryCodeInfo }}
<li v-for="code in recoveryCodes" :key="code">{{ code }}</li>
</div>
</div>

<MkButton v-else-if="!twoFactorData && !$i.twoFactorEnabled" @click="registerTOTP">{{ i18n.ts._2fa.registerTOTP }}</MkButton>
Expand Down Expand Up @@ -83,6 +88,8 @@ withDefaults(defineProps<{
const twoFactorData = ref<any>(null);
const supportsCredentials = ref(!!navigator.credentials);
const usePasswordLessLogin = $computed(() => $i!.usePasswordLessLogin);
const showRecoveryCode = ref(false);
const recoveryCodes = ref<string[]>([]);

async function registerTOTP() {
const password = await os.inputText({
Expand Down Expand Up @@ -155,6 +162,28 @@ function renewTOTP() {
});
}

async function generateRecoveryCode() {
const confirm = await os.confirm({
type: 'warning',
title: i18n.ts._2fa.generateRecoveryCode,
text: i18n.ts._2fa.generateRecoveryCodeConfirm,
okText: i18n.ts._2fa.generateRecoveryCodeOK,
cancelText: i18n.ts._2fa.generateRecoveryCodeCancel,
});
if (confirm.canceled) return;

const password = await os.inputText({
title: i18n.ts.password,
type: 'password',
autocomplete: 'current-password',
});
const codes = await os.apiWithDialog('i/2fa/generate-recovery-codes', {
password: password.result,
});
recoveryCodes.value = codes;
showRecoveryCode.value = true;
}

async function unregisterKey(key) {
const confirm = await os.confirm({
type: 'question',
Expand Down