Skip to content

Commit

Permalink
fix(BodyHashStream): Skip header
Browse files Browse the repository at this point in the history
  • Loading branch information
andris9 committed Oct 21, 2024
1 parent d19b1f2 commit 3da03d2
Showing 1 changed file with 6 additions and 45 deletions.
51 changes: 6 additions & 45 deletions lib/dkim/body/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const { SimpleHash } = require('./simple');
const { RelaxedHash } = require('./relaxed');
const { Transform } = require('node:stream');
const { MessageParser } = require('../message-parser');

const dkimBody = (canonicalization, ...options) => {
canonicalization = (canonicalization || 'simple/simple').toString().split('/').pop().toLowerCase().trim();
Expand All @@ -20,50 +19,15 @@ const dkimBody = (canonicalization, ...options) => {
}
};

class MessageHasher extends MessageParser {
constructor(canonicalization, ...options) {
super();
this.hasher = dkimBody(canonicalization, ...options);
this.bodyHash = null;
}

async nextChunk(chunk) {
this.hasher.update(chunk);
}

async finalChunk() {
this.bodyHash = this.hasher.digest('base64');
}
}

class BodyHashStream extends Transform {
constructor(canonicalization, ...options) {
super();

this.finished = false;
this.finishCb = null;

this.byteLength = 0;

this.messageHasher = new MessageHasher(canonicalization, ...options);
this.bodyHash = null;
this.messageHasher.once('finish', () => this.finishHashing());
this.messageHasher.once('end', () => this.finishHashing());
this.messageHasher.once('error', err => this.destroy(err));
}

finishHashing() {
if (this.finished || !this.finishCb) {
return;
}
this.finished = true;
let done = this.finishCb;
this.finishCb = null;

this.bodyHash = this.messageHasher.bodyHash;
this.emit('hash', this.bodyHash);
this.hasher = dkimBody(canonicalization, ...options);

done();
this.bodyHash = null;
}

_transform(chunk, encoding, done) {
Expand All @@ -77,19 +41,16 @@ class BodyHashStream extends Transform {

this.byteLength += chunk.length;

this.hasher.update(chunk);
this.push(chunk);

if (this.messageHasher.write(chunk) === false) {
// wait for drain
return this.messageHasher.once('drain', done);
}

done();
}

_flush(done) {
this.finishCb = done;
this.messageHasher.end();
this.bodyHash = this.hasher.digest('base64');
this.emit('hash', this.bodyHash);
done();
}
}

Expand Down

0 comments on commit 3da03d2

Please sign in to comment.