|
| 1 | +import { createHmac } from "crypto"; |
| 2 | +import { ConfigurationError } from "@pipedream/platform"; |
| 3 | +import app from "../../aftership.app.mjs"; |
| 4 | + |
| 5 | +export default { |
| 6 | + props: { |
| 7 | + app, |
| 8 | + http: { |
| 9 | + type: "$.interface.http", |
| 10 | + customResponse: true, |
| 11 | + }, |
| 12 | + webhookSecret: { |
| 13 | + type: "string", |
| 14 | + label: "Secret", |
| 15 | + description: "The secret for the webhook. You can find it in `Tracking -> Settings -> Webhooks -> Webhook secret`", |
| 16 | + }, |
| 17 | + }, |
| 18 | + hooks: { |
| 19 | + async deploy() { |
| 20 | + if (!this.webhookSecret) { |
| 21 | + console.log("No webhook secret was provided, skipping deployment"); |
| 22 | + throw new ConfigurationError("No webhook secret was provided, skipping deployment"); |
| 23 | + } |
| 24 | + |
| 25 | + const { data: { trackings } } = await this.app.listTrackings({ |
| 26 | + params: { |
| 27 | + page: 1, |
| 28 | + limit: 25, |
| 29 | + }, |
| 30 | + }); |
| 31 | + |
| 32 | + trackings |
| 33 | + .slice(0, 25) |
| 34 | + .reverse() |
| 35 | + .forEach((tracking) => { |
| 36 | + this.processResource({ |
| 37 | + event: this.getEventName(), |
| 38 | + event_id: tracking.id, |
| 39 | + msg: tracking, |
| 40 | + ts: Date.parse(tracking.updated_at) / 1000, |
| 41 | + }); |
| 42 | + }); |
| 43 | + }, |
| 44 | + }, |
| 45 | + methods: { |
| 46 | + generateMeta() { |
| 47 | + throw new ConfigurationError("generateMeta is not implemented"); |
| 48 | + }, |
| 49 | + getEventName() { |
| 50 | + throw new ConfigurationError("getEventName is not implemented"); |
| 51 | + }, |
| 52 | + isSignatureValid(bodyRaw, signature) { |
| 53 | + const { webhookSecret } = this; |
| 54 | + if (!webhookSecret) { |
| 55 | + console.log("No webhook secret found, skipping signature verification"); |
| 56 | + return true; |
| 57 | + } |
| 58 | + const hash = createHmac("sha256", webhookSecret) |
| 59 | + .update(bodyRaw) |
| 60 | + .digest("base64"); |
| 61 | + return hash === signature; |
| 62 | + }, |
| 63 | + processResource(resource) { |
| 64 | + this.$emit(resource, this.generateMeta(resource)); |
| 65 | + }, |
| 66 | + }, |
| 67 | + async run({ |
| 68 | + body, bodyRaw, headers, |
| 69 | + }) { |
| 70 | + const signature = headers["aftership-hmac-sha256"]; |
| 71 | + |
| 72 | + if (!this.isSignatureValid(bodyRaw, signature)) { |
| 73 | + console.log("Could not verify incoming webhook signature"); |
| 74 | + return this.http.respond({ |
| 75 | + status: 401, |
| 76 | + }); |
| 77 | + } |
| 78 | + |
| 79 | + this.http.respond({ |
| 80 | + status: 200, |
| 81 | + }); |
| 82 | + |
| 83 | + this.processResource(body); |
| 84 | + }, |
| 85 | +}; |
0 commit comments