Skip to content

Instantly share code, notes, and snippets.

@jokamjohn
Last active October 10, 2023 18:14
Show Gist options
  • Save jokamjohn/f394a8c9a765c7970b53d49909888029 to your computer and use it in GitHub Desktop.
Save jokamjohn/f394a8c9a765c7970b53d49909888029 to your computer and use it in GitHub Desktop.
encrption
import { Injectable } from '@nestjs/common';
import * as crypto from 'crypto';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class EncryptionService {
private readonly encryptionKey: Buffer;
private readonly algorithm = 'aes-256-cbc';
private readonly iv = crypto.randomBytes(16);
constructor(private readonly configService: ConfigService) {
this.encryptionKey = Buffer.from(
this.configService.getOrThrow<string>('app.encryptionKey'),
'hex',
);
}
encrypt(payload: any) {
const cipher = crypto.createCipheriv(
this.algorithm,
this.encryptionKey,
this.iv,
);
let encrypted = cipher.update(JSON.stringify(payload), 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
decrypt(data: any) {
const decipher = crypto.createDecipheriv(
this.algorithm,
this.encryptionKey,
this.iv,
);
let decrypted = decipher.update(data, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return JSON.parse(decrypted);
}
}
import { Injectable } from '@nestjs/common';
import { EncryptionService } from '../encryption';
import { InngestMiddleware } from 'inngest';
@Injectable()
export class QueueInngestMiddleware {
constructor(private readonly encryptionService: EncryptionService) {}
middleware() {
return new InngestMiddleware({
name: 'Encryption',
// @ts-ignore
init: () => {
return {
onSendEvent: () => {
return {
transformInput: ({ payloads }) => {
return {
payloads: payloads.map((payload) => ({
...payload,
data: payload.data
? this.encryptionService.encrypt(payload.data)
: undefined,
})),
};
},
};
},
onFunctionRun: () => {
return {
transformInput: ({ ctx, steps }) => {
return {
steps: steps.map((step) => ({
...step,
data: step.data
? this.encryptionService.decrypt(step.data)
: undefined,
})),
ctx: {
event: ctx.event
? this.encryptionService.decrypt(ctx.event)
: undefined,
events: ctx.events
? ctx.events.map(this.encryptionService.decrypt)
: undefined,
} as object,
};
},
transformOutput: (ctx) => {
return {
result: {
data: ctx.result.data
? this.encryptionService.encrypt(ctx.result.data)
: undefined,
},
};
},
};
},
};
},
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment