トークン系の乱数ソースではcryptoを使うように (#6200)

This commit is contained in:
MeiMei 2020-03-29 23:16:36 +09:00 committed by GitHub
parent 19dd992062
commit edfbb37a37
5 changed files with 29 additions and 8 deletions

21
src/misc/secure-rndstr.ts Normal file
View File

@ -0,0 +1,21 @@
import * as crypto from 'crypto';
const L_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';
const LU_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
export function secureRndstr(length = 32, useLU = true): string {
const chars = useLU ? LU_CHARS : L_CHARS;
const chars_len = chars.length;
let str = '';
for (let i = 0; i < length; i++) {
let rand = Math.floor((crypto.randomBytes(1).readUInt8(0) / 0xFF) * chars_len);
if (rand === chars_len) {
rand = chars_len - 1;
}
str += chars.charAt(rand);
}
return str;
}

View File

@ -1,3 +1,3 @@
import rndstr from 'rndstr';
import { secureRndstr } from '../../../misc/secure-rndstr';
export default () => rndstr('a-zA-Z0-9', 16);
export default () => secureRndstr(16, true);

View File

@ -1,9 +1,9 @@
import rndstr from 'rndstr';
import $ from 'cafy';
import define from '../../define';
import { Apps } from '../../../../models';
import { genId } from '../../../../misc/gen-id';
import { unique } from '../../../../prelude/array';
import { secureRndstr } from '../../../../misc/secure-rndstr';
export const meta = {
tags: ['app'],
@ -60,7 +60,7 @@ export const meta = {
export default define(meta, async (ps, user) => {
// Generate secret
const secret = rndstr('a-zA-Z0-9', 32);
const secret = secureRndstr(32, true);
// for backward compatibility
const permission = unique(ps.permission.map(v => v.replace(/^(.+)(\/|-)(read|write)$/, '$3:$1')));

View File

@ -1,4 +1,3 @@
import rndstr from 'rndstr';
import * as crypto from 'crypto';
import $ from 'cafy';
import define from '../../define';
@ -6,6 +5,7 @@ import { ApiError } from '../../error';
import { AuthSessions, AccessTokens, Apps } from '../../../../models';
import { genId } from '../../../../misc/gen-id';
import { ensure } from '../../../../prelude/ensure';
import { secureRndstr } from '../../../../misc/secure-rndstr';
export const meta = {
tags: ['auth'],
@ -39,7 +39,7 @@ export default define(meta, async (ps, user) => {
}
// Generate access token
const accessToken = rndstr('a-zA-Z0-9', 32);
const accessToken = secureRndstr(32, true);
// Fetch exist access token
const exist = await AccessTokens.findOne({

View File

@ -1,8 +1,8 @@
import rndstr from 'rndstr';
import $ from 'cafy';
import define from '../../define';
import { AccessTokens } from '../../../../models';
import { genId } from '../../../../misc/gen-id';
import { secureRndstr } from '../../../../misc/secure-rndstr';
export const meta = {
tags: ['auth'],
@ -36,7 +36,7 @@ export const meta = {
export default define(meta, async (ps, user) => {
// Generate access token
const accessToken = rndstr('a-zA-Z0-9', 32);
const accessToken = secureRndstr(32, true);
// Insert access token doc
await AccessTokens.save({