|
| 1 | +const crypto = require('crypto') |
| 2 | +const { DateTime } = require('luxon') |
| 3 | +const { parse: parseUrl } = require('url') |
| 4 | + |
| 5 | +module.exports.requestHooks = [ |
| 6 | + async context => { |
| 7 | + const { store, request } = context |
| 8 | + const keyId = await store.getItem('keyId') |
| 9 | + let privateKey = await store.getItem('privateKey') |
| 10 | + privateKey = `-----BEGIN PRIVATE KEY-----\n${privateKey}\n-----END PRIVATE KEY-----` |
| 11 | + |
| 12 | + const parsedUrl = parseUrl(request.getUrl()) |
| 13 | + |
| 14 | + const algorithmBits = 256 |
| 15 | + const hashAlgorithm = `sha${algorithmBits}` |
| 16 | + const digestAlgorithm = `SHA-${algorithmBits}` |
| 17 | + const signAlgorithm = `RSA-SHA${algorithmBits}` |
| 18 | + |
| 19 | + const date = DateTime.utc().toRFC2822() |
| 20 | + |
| 21 | + const digestHash = crypto.createHash(hashAlgorithm) |
| 22 | + const digest = digestHash.update(request.getBodyText()).digest('base64') |
| 23 | + |
| 24 | + const signatureString = [] |
| 25 | + signatureString.push(`(request-target): ${request.getMethod().toLowerCase()} ${parsedUrl.path}`) |
| 26 | + signatureString.push(`host: ${parsedUrl.hostname}`) |
| 27 | + signatureString.push(`digest: ${digestAlgorithm}=${digest}`) |
| 28 | + signatureString.push(`date: ${date}`) |
| 29 | + if (request.hasHeader('Content-Type')) signatureString.push(`content-type: ${request.getHeader('Content-Type')}`) |
| 30 | + const signature = signatureString.join('\n') |
| 31 | + |
| 32 | + const signatureSign = crypto.createSign(signAlgorithm) |
| 33 | + const signedSignature = signatureSign.update(signature).sign(privateKey, 'base64') |
| 34 | + |
| 35 | + const authorization = `Signature keyId="${keyId}", algorithm="${signAlgorithm.toLowerCase()}", headers="(request-target) host digest date${request.hasHeader('Content-Type') ? ' content-type' : ''}", signature="${signedSignature}"` |
| 36 | + |
| 37 | + request.setHeader('Digest', `${digestAlgorithm}=${digest}`) |
| 38 | + request.setHeader('Date', date) |
| 39 | + request.setHeader('Authorization', authorization) |
| 40 | + } |
| 41 | +] |
| 42 | + |
| 43 | +module.exports.templateTags = [{ |
| 44 | + name: 'httpsignature', |
| 45 | + displayName: 'HTTP Signature', |
| 46 | + description: 'sign http requests', |
| 47 | + |
| 48 | + args: [ |
| 49 | + { |
| 50 | + displayName: 'Key ID', |
| 51 | + type: 'string' |
| 52 | + }, |
| 53 | + { |
| 54 | + displayName: 'Private Key', |
| 55 | + type: 'string' |
| 56 | + } |
| 57 | + ], |
| 58 | + |
| 59 | + async run (context, keyId, privateKey) { |
| 60 | + await context.store.setItem('keyId', keyId) |
| 61 | + await context.store.setItem('privateKey', privateKey) |
| 62 | + return ' ' |
| 63 | + } |
| 64 | +}] |
0 commit comments