refactor(backend): Improve UUID generation (#11286)

* Replace with `crypto.randomUUID()`

* Remove uuid
This commit is contained in:
woxtu 2023-07-15 18:39:38 +09:00 committed by GitHub
parent 9d5dd7201e
commit b392f44b81
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 25 additions and 34 deletions

View file

@ -158,7 +158,6 @@
"typescript": "5.1.6", "typescript": "5.1.6",
"ulid": "2.3.0", "ulid": "2.3.0",
"unzipper": "0.10.14", "unzipper": "0.10.14",
"uuid": "9.0.0",
"vary": "1.1.2", "vary": "1.1.2",
"web-push": "3.6.3", "web-push": "3.6.3",
"ws": "8.13.0", "ws": "8.13.0",
@ -201,7 +200,6 @@
"@types/tinycolor2": "1.4.3", "@types/tinycolor2": "1.4.3",
"@types/tmp": "0.2.3", "@types/tmp": "0.2.3",
"@types/unzipper": "0.10.6", "@types/unzipper": "0.10.6",
"@types/uuid": "9.0.2",
"@types/vary": "1.1.0", "@types/vary": "1.1.0",
"@types/web-push": "3.3.2", "@types/web-push": "3.3.2",
"@types/websocket": "1.0.5", "@types/websocket": "1.0.5",

View file

@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import bcrypt from 'bcryptjs'; import bcrypt from 'bcryptjs';
import { v4 as uuid } from 'uuid';
import { IsNull, DataSource } from 'typeorm'; import { IsNull, DataSource } from 'typeorm';
import { genRsaKeyPair } from '@/misc/gen-key-pair.js'; import { genRsaKeyPair } from '@/misc/gen-key-pair.js';
import { User } from '@/models/entities/User.js'; import { User } from '@/models/entities/User.js';
@ -24,7 +24,7 @@ export class CreateSystemUserService {
@bindThis @bindThis
public async createSystemUser(username: string): Promise<User> { public async createSystemUser(username: string): Promise<User> {
const password = uuid(); const password = randomUUID();
// Generate hash of password // Generate hash of password
const salt = await bcrypt.genSalt(8); const salt = await bcrypt.genSalt(8);

View file

@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import sharp from 'sharp'; import sharp from 'sharp';
import { sharpBmp } from 'sharp-read-bmp'; import { sharpBmp } from 'sharp-read-bmp';
import { IsNull } from 'typeorm'; import { IsNull } from 'typeorm';
@ -162,7 +162,7 @@ export class DriveService {
?? `${ meta.objectStorageUseSSL ? 'https' : 'http' }://${ meta.objectStorageEndpoint }${ meta.objectStoragePort ? `:${meta.objectStoragePort}` : '' }/${ meta.objectStorageBucket }`; ?? `${ meta.objectStorageUseSSL ? 'https' : 'http' }://${ meta.objectStorageEndpoint }${ meta.objectStoragePort ? `:${meta.objectStoragePort}` : '' }/${ meta.objectStorageBucket }`;
// for original // for original
const key = `${meta.objectStoragePrefix}/${uuid()}${ext}`; const key = `${meta.objectStoragePrefix}/${randomUUID()}${ext}`;
const url = `${ baseUrl }/${ key }`; const url = `${ baseUrl }/${ key }`;
// for alts // for alts
@ -179,7 +179,7 @@ export class DriveService {
]; ];
if (alts.webpublic) { if (alts.webpublic) {
webpublicKey = `${meta.objectStoragePrefix}/webpublic-${uuid()}.${alts.webpublic.ext}`; webpublicKey = `${meta.objectStoragePrefix}/webpublic-${randomUUID()}.${alts.webpublic.ext}`;
webpublicUrl = `${ baseUrl }/${ webpublicKey }`; webpublicUrl = `${ baseUrl }/${ webpublicKey }`;
this.registerLogger.info(`uploading webpublic: ${webpublicKey}`); this.registerLogger.info(`uploading webpublic: ${webpublicKey}`);
@ -187,7 +187,7 @@ export class DriveService {
} }
if (alts.thumbnail) { if (alts.thumbnail) {
thumbnailKey = `${meta.objectStoragePrefix}/thumbnail-${uuid()}.${alts.thumbnail.ext}`; thumbnailKey = `${meta.objectStoragePrefix}/thumbnail-${randomUUID()}.${alts.thumbnail.ext}`;
thumbnailUrl = `${ baseUrl }/${ thumbnailKey }`; thumbnailUrl = `${ baseUrl }/${ thumbnailKey }`;
this.registerLogger.info(`uploading thumbnail: ${thumbnailKey}`); this.registerLogger.info(`uploading thumbnail: ${thumbnailKey}`);
@ -212,9 +212,9 @@ export class DriveService {
return await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0])); return await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0]));
} else { // use internal storage } else { // use internal storage
const accessKey = uuid(); const accessKey = randomUUID();
const thumbnailAccessKey = 'thumbnail-' + uuid(); const thumbnailAccessKey = 'thumbnail-' + randomUUID();
const webpublicAccessKey = 'webpublic-' + uuid(); const webpublicAccessKey = 'webpublic-' + randomUUID();
const url = this.internalStorageService.saveFromPath(accessKey, path); const url = this.internalStorageService.saveFromPath(accessKey, path);
@ -584,9 +584,9 @@ export class DriveService {
if (isLink) { if (isLink) {
file.url = url; file.url = url;
// ローカルプロキシ用 // ローカルプロキシ用
file.accessKey = uuid(); file.accessKey = randomUUID();
file.thumbnailAccessKey = 'thumbnail-' + uuid(); file.thumbnailAccessKey = 'thumbnail-' + randomUUID();
file.webpublicAccessKey = 'webpublic-' + uuid(); file.webpublicAccessKey = 'webpublic-' + randomUUID();
} }
} }
@ -713,9 +713,9 @@ export class DriveService {
webpublicUrl: null, webpublicUrl: null,
storedInternal: false, storedInternal: false,
// ローカルプロキシ用 // ローカルプロキシ用
accessKey: uuid(), accessKey: randomUUID(),
thumbnailAccessKey: 'thumbnail-' + uuid(), thumbnailAccessKey: 'thumbnail-' + randomUUID(),
webpublicAccessKey: 'webpublic-' + uuid(), webpublicAccessKey: 'webpublic-' + randomUUID(),
}); });
} else { } else {
this.driveFilesRepository.delete(file.id); this.driveFilesRepository.delete(file.id);

View file

@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import type { IActivity } from '@/core/activitypub/type.js'; import type { IActivity } from '@/core/activitypub/type.js';
import type { DriveFile } from '@/models/entities/DriveFile.js'; import type { DriveFile } from '@/models/entities/DriveFile.js';
import type { Webhook, webhookEventTypes } from '@/models/entities/Webhook.js'; import type { Webhook, webhookEventTypes } from '@/models/entities/Webhook.js';
@ -416,7 +416,7 @@ export class QueueService {
to: webhook.url, to: webhook.url,
secret: webhook.secret, secret: webhook.secret,
createdAt: Date.now(), createdAt: Date.now(),
eventId: uuid(), eventId: randomUUID(),
}; };
return this.webhookDeliverQueue.add(webhook.id, data, { return this.webhookDeliverQueue.add(webhook.id, data, {

View file

@ -1,7 +1,6 @@
import { createPublicKey } from 'node:crypto'; import { createPublicKey, randomUUID } from 'node:crypto';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { In } from 'typeorm'; import { In } from 'typeorm';
import { v4 as uuid } from 'uuid';
import * as mfm from 'mfm-js'; import * as mfm from 'mfm-js';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import type { Config } from '@/config.js'; import type { Config } from '@/config.js';
@ -613,7 +612,7 @@ export class ApRendererService {
@bindThis @bindThis
public addContext<T extends IObject>(x: T): T & { '@context': any; id: string; } { public addContext<T extends IObject>(x: T): T & { '@context': any; id: string; } {
if (typeof x === 'object' && x.id == null) { if (typeof x === 'object' && x.id == null) {
x.id = `${this.config.url}/${uuid()}`; x.id = `${this.config.url}/${randomUUID()}`;
} }
return Object.assign({ return Object.assign({

View file

@ -1,8 +1,8 @@
import { randomUUID } from 'node:crypto';
import { pipeline } from 'node:stream'; import { pipeline } from 'node:stream';
import * as fs from 'node:fs'; import * as fs from 'node:fs';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import { DI } from '@/di-symbols.js'; import { DI } from '@/di-symbols.js';
import { getIpHash } from '@/misc/get-ip-hash.js'; import { getIpHash } from '@/misc/get-ip-hash.js';
import type { LocalUser, User } from '@/models/entities/User.js'; import type { LocalUser, User } from '@/models/entities/User.js';
@ -362,7 +362,7 @@ export class ApiCallService implements OnApplicationShutdown {
if (err instanceof ApiError || err instanceof AuthenticationError) { if (err instanceof ApiError || err instanceof AuthenticationError) {
throw err; throw err;
} else { } else {
const errId = uuid(); const errId = randomUUID();
this.logger.error(`Internal error occurred in ${ep.name}: ${err.message}`, { this.logger.error(`Internal error occurred in ${ep.name}: ${err.message}`, {
ep: ep.name, ep: ep.name,
ps: data, ps: data,

View file

@ -1,4 +1,4 @@
import { v4 as uuid } from 'uuid'; import { randomUUID } from 'node:crypto';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js'; import { Endpoint } from '@/server/api/endpoint-base.js';
import type { AppsRepository, AuthSessionsRepository } from '@/models/index.js'; import type { AppsRepository, AuthSessionsRepository } from '@/models/index.js';
@ -71,7 +71,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> {
} }
// Generate token // Generate token
const token = uuid(); const token = randomUUID();
// Create session token document // Create session token document
const doc = await this.authSessionsRepository.insert({ const doc = await this.authSessionsRepository.insert({

View file

@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { dirname } from 'node:path'; import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { Inject, Injectable } from '@nestjs/common'; import { Inject, Injectable } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import { createBullBoard } from '@bull-board/api'; import { createBullBoard } from '@bull-board/api';
import { BullAdapter } from '@bull-board/api/bullAdapter.js'; import { BullAdapter } from '@bull-board/api/bullAdapter.js';
import { FastifyAdapter } from '@bull-board/fastify'; import { FastifyAdapter } from '@bull-board/fastify';
@ -676,7 +676,7 @@ export class ClientServerService {
}); });
fastify.setErrorHandler(async (error, request, reply) => { fastify.setErrorHandler(async (error, request, reply) => {
const errId = uuid(); const errId = randomUUID();
this.clientLoggerService.logger.error(`Internal error occured in ${request.routerPath}: ${error.message}`, { this.clientLoggerService.logger.error(`Internal error occured in ${request.routerPath}: ${error.message}`, {
path: request.routerPath, path: request.routerPath,
params: request.params, params: request.params,

View file

@ -380,9 +380,6 @@ importers:
unzipper: unzipper:
specifier: 0.10.14 specifier: 0.10.14
version: 0.10.14 version: 0.10.14
uuid:
specifier: 9.0.0
version: 9.0.0
vary: vary:
specifier: 1.1.2 specifier: 1.1.2
version: 1.1.2 version: 1.1.2
@ -586,9 +583,6 @@ importers:
'@types/unzipper': '@types/unzipper':
specifier: 0.10.6 specifier: 0.10.6
version: 0.10.6 version: 0.10.6
'@types/uuid':
specifier: 9.0.2
version: 9.0.2
'@types/vary': '@types/vary':
specifier: 1.1.0 specifier: 1.1.0
version: 1.1.0 version: 1.1.0