1 import { Request } from 'express'
2 import { BCRYPT_SALT_SIZE, HTTP_SIGNATURE, PRIVATE_RSA_KEY_SIZE } from '../initializers/constants'
3 import { ActorModel } from '../models/activitypub/actor'
4 import { createPrivateKey, getPublicKey, promisify1, promisify2, sha256 } from './core-utils'
5 import { jsig, jsonld } from './custom-jsonld-signature'
6 import { logger } from './logger'
7 import { cloneDeep } from 'lodash'
8 import { createVerify } from 'crypto'
9 import { buildDigest } from '../lib/job-queue/handlers/utils/activitypub-http-utils'
10 import * as bcrypt from 'bcrypt'
11 import { MActor } from '../typings/models'
13 const bcryptComparePromise = promisify2<any, string, boolean>(bcrypt.compare)
14 const bcryptGenSaltPromise = promisify1<number, string>(bcrypt.genSalt)
15 const bcryptHashPromise = promisify2<any, string | number, string>(bcrypt.hash)
17 const httpSignature = require('http-signature')
19 async function createPrivateAndPublicKeys () {
20 logger.info('Generating a RSA key...')
22 const { key } = await createPrivateKey(PRIVATE_RSA_KEY_SIZE)
23 const { publicKey } = await getPublicKey(key)
25 return { privateKey: key, publicKey }
28 // User password checks
30 function comparePassword (plainPassword: string, hashPassword: string) {
31 return bcryptComparePromise(plainPassword, hashPassword)
34 async function cryptPassword (password: string) {
35 const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
37 return bcryptHashPromise(password, salt)
42 function isHTTPSignatureDigestValid (rawBody: Buffer, req: Request): boolean {
43 if (req.headers[HTTP_SIGNATURE.HEADER_NAME] && req.headers['digest']) {
44 return buildDigest(rawBody.toString()) === req.headers['digest']
50 function isHTTPSignatureVerified (httpSignatureParsed: any, actor: MActor): boolean {
51 return httpSignature.verifySignature(httpSignatureParsed, actor.publicKey) === true
54 function parseHTTPSignature (req: Request, clockSkew?: number) {
55 return httpSignature.parse(req, { authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME, clockSkew })
60 async function isJsonLDSignatureVerified (fromActor: MActor, signedDocument: any): Promise<boolean> {
61 if (signedDocument.signature.type === 'RsaSignature2017') {
63 const res = await isJsonLDRSA2017Verified(fromActor, signedDocument)
64 // Success? If no, try with our library
65 if (res === true) return true
68 const publicKeyObject = {
69 '@context': jsig.SECURITY_CONTEXT_URL,
71 type: 'CryptographicKey',
73 publicKeyPem: fromActor.publicKey
76 const publicKeyOwnerObject = {
77 '@context': jsig.SECURITY_CONTEXT_URL,
79 publicKey: [ publicKeyObject ]
83 publicKey: publicKeyObject,
84 publicKeyOwner: publicKeyOwnerObject
88 .verify(signedDocument, options)
89 .then((result: { verified: boolean }) => result.verified)
91 logger.error('Cannot check signature.', { err })
96 // Backward compatibility with "other" implementations
97 async function isJsonLDRSA2017Verified (fromActor: MActor, signedDocument: any) {
98 function hash (obj: any): Promise<any> {
99 return jsonld.promises
101 algorithm: 'URDNA2015',
102 format: 'application/n-quads'
104 .then(res => sha256(res))
107 const signatureCopy = cloneDeep(signedDocument.signature)
108 Object.assign(signatureCopy, {
110 'https://w3id.org/security/v1',
111 { RsaSignature2017: 'https://w3id.org/security#RsaSignature2017' }
114 delete signatureCopy.type
115 delete signatureCopy.id
116 delete signatureCopy.signatureValue
118 const docWithoutSignature = cloneDeep(signedDocument)
119 delete docWithoutSignature.signature
121 const [ documentHash, optionsHash ] = await Promise.all([
122 hash(docWithoutSignature),
126 const toVerify = optionsHash + documentHash
128 const verify = createVerify('RSA-SHA256')
129 verify.update(toVerify, 'utf8')
131 return verify.verify(fromActor.publicKey, signedDocument.signature.signatureValue, 'base64')
134 function signJsonLDObject (byActor: MActor, data: any) {
136 privateKeyPem: byActor.privateKey,
137 creator: byActor.url,
138 algorithm: 'RsaSignature2017'
141 return jsig.promises.sign(data, options)
144 // ---------------------------------------------------------------------------
147 isHTTPSignatureDigestValid,
149 isHTTPSignatureVerified,
150 isJsonLDSignatureVerified,
152 createPrivateAndPublicKeys,
157 // ---------------------------------------------------------------------------