Skip to content

Instantly share code, notes, and snippets.

@djfarrelly
Created September 22, 2023 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djfarrelly/baeb32b10f1fc7691ae94baad6bf5e4c to your computer and use it in GitHub Desktop.
Save djfarrelly/baeb32b10f1fc7691ae94baad6bf5e4c to your computer and use it in GitHub Desktop.
Inngest - Encryption middleware
import { InngestMiddleware } from "inngest";
export const encryptionMiddleware = (
key: string = process.env.INNGEST_ENCRYPTION_KEY || ""
) => {
if (!key) {
throw new Error("Must provide an encryption key");
}
const prefix = "__ENCRYPTED__";
// Change `encrypt` to whatever implementation you want - obviously not this.
const encrypt = <T = string>(value: unknown): T => {
return `${prefix}${JSON.stringify(value)
.split("")
.reverse()
.join("")}` as T;
};
// Change `decrypt` to whatever implementation you want - obviously not this.
const decrypt = <T>(value: T): T => {
if (typeof value === "string" && value.startsWith(prefix)) {
return JSON.parse(
value.slice(prefix.length).split("").reverse().join("")
);
}
// Assume the value is not encrypted, e.g. sent from the UI or something.
return value;
};
return new InngestMiddleware({
name: "Encryption",
init: () => {
return {
onSendEvent: () => {
return {
transformInput: ({ payloads }) => {
return {
payloads: payloads.map((payload) => ({
...payload,
data: payload.data ? encrypt(payload.data) : undefined,
})),
};
},
};
},
onFunctionRun: () => {
return {
transformInput: ({ ctx, steps }) => {
return {
steps: steps.map((step) => ({
...step,
data: step.data ? decrypt(step.data) : undefined,
})),
ctx: {
event: ctx.event ? decrypt(ctx.event) : undefined,
events: ctx.events ? ctx.events.map(decrypt) : undefined,
} as {},
};
},
transformOutput: (ctx) => {
return {
result: {
data: ctx.result.data ? encrypt(ctx.result.data) : undefined,
},
};
},
};
},
};
},
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment