ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

peertube-crypto.ts 3.7 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import httpSignature from '@peertube/http-signature'
  2. import { sha256 } from '@peertube/peertube-node-utils'
  3. import { createCipheriv, createDecipheriv } from 'crypto'
  4. import { Request } from 'express'
  5. import { BCRYPT_SALT_SIZE, ENCRYPTION, HTTP_SIGNATURE, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants.js'
  6. import { MActor } from '../types/models/index.js'
  7. import { generateRSAKeyPairPromise, randomBytesPromise, scryptPromise } from './core-utils.js'
  8. import { logger } from './logger.js'
  9. function createPrivateAndPublicKeys () {
  10. logger.info('Generating a RSA key...')
  11. return generateRSAKeyPairPromise(PRIVATE_RSA_KEY_SIZE)
  12. }
  13. // ---------------------------------------------------------------------------
  14. // User password checks
  15. // ---------------------------------------------------------------------------
  16. async function comparePassword (plainPassword: string, hashPassword: string) {
  17. if (!plainPassword) return false
  18. const { compare } = await import('bcrypt')
  19. return compare(plainPassword, hashPassword)
  20. }
  21. async function cryptPassword (password: string) {
  22. const { genSalt, hash } = await import('bcrypt')
  23. const salt = await genSalt(BCRYPT_SALT_SIZE)
  24. return hash(password, salt)
  25. }
  26. // ---------------------------------------------------------------------------
  27. // HTTP Signature
  28. // ---------------------------------------------------------------------------
  29. function isHTTPSignatureDigestValid (rawBody: Buffer, req: Request): boolean {
  30. if (req.headers[HTTP_SIGNATURE.HEADER_NAME] && req.headers['digest']) {
  31. return buildDigest(rawBody.toString()) === req.headers['digest']
  32. }
  33. return true
  34. }
  35. function isHTTPSignatureVerified (httpSignatureParsed: any, actor: MActor): boolean {
  36. return httpSignature.verifySignature(httpSignatureParsed, actor.publicKey) === true
  37. }
  38. function parseHTTPSignature (req: Request, clockSkew?: number) {
  39. const requiredHeaders = req.method === 'POST'
  40. ? [ '(request-target)', 'host', 'digest' ]
  41. : [ '(request-target)', 'host' ]
  42. const parsed = httpSignature.parse(req, { clockSkew, headers: requiredHeaders })
  43. const parsedHeaders = parsed.params.headers
  44. if (!parsedHeaders.includes('date') && !parsedHeaders.includes('(created)')) {
  45. throw new Error(`date or (created) must be included in signature`)
  46. }
  47. return parsed
  48. }
  49. // ---------------------------------------------------------------------------
  50. function buildDigest (body: any) {
  51. const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
  52. return 'SHA-256=' + sha256(rawBody, 'base64')
  53. }
  54. // ---------------------------------------------------------------------------
  55. // Encryption
  56. // ---------------------------------------------------------------------------
  57. async function encrypt (str: string, secret: string) {
  58. const iv = await randomBytesPromise(ENCRYPTION.IV)
  59. const key = await scryptPromise(secret, ENCRYPTION.SALT, 32)
  60. const cipher = createCipheriv(ENCRYPTION.ALGORITHM, key, iv)
  61. let encrypted = iv.toString(ENCRYPTION.ENCODING) + ':'
  62. encrypted += cipher.update(str, 'utf8', ENCRYPTION.ENCODING)
  63. encrypted += cipher.final(ENCRYPTION.ENCODING)
  64. return encrypted
  65. }
  66. async function decrypt (encryptedArg: string, secret: string) {
  67. const [ ivStr, encryptedStr ] = encryptedArg.split(':')
  68. const iv = Buffer.from(ivStr, 'hex')
  69. const key = await scryptPromise(secret, ENCRYPTION.SALT, 32)
  70. const decipher = createDecipheriv(ENCRYPTION.ALGORITHM, key, iv)
  71. return decipher.update(encryptedStr, ENCRYPTION.ENCODING, 'utf8') + decipher.final('utf8')
  72. }
  73. // ---------------------------------------------------------------------------
  74. export {
  75. isHTTPSignatureDigestValid,
  76. parseHTTPSignature,
  77. isHTTPSignatureVerified,
  78. buildDigest,
  79. comparePassword,
  80. createPrivateAndPublicKeys,
  81. cryptPassword,
  82. encrypt,
  83. decrypt
  84. }