Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REC-359] provide webhook verification nodejs example #65

Merged
merged 4 commits into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions nodejs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,5 @@ tlSigning.verify({
headers: allWebhookHeaders,
});
```

See [full example](./examples/webhook-server/).
27 changes: 27 additions & 0 deletions nodejs/examples/webhook-server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# NodeJS webhook server example
A http server than can receive and verify signed TrueLayer webhooks.

## Run

First, build the signing lib
```sh
# in the `truelayer-signing/nodejs` dir
yarn build
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it just yarn?

Suggested change
yarn build
yarn

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe that works, but build is the specific script that does actually builds the lib.js file:
https://github.com/TrueLayer/truelayer-signing/blob/main/nodejs/package.json#L9

Copy link
Contributor

@alexheretic alexheretic May 3, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see the directory, wouldn't just running yarn in the examples/webhook-server dir work fine in any case?

yarn is playing up for me at the moment because of jfrog, but npm i in the webhook-server does the right thing so I assume running yarn would too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Judging by @jdon's comment in the slack thread, it doesn't seem to work properly (it will pull the path dependency, but doesn't run the build script to build)

```

Then, run the server
```sh
# in the `examples/webhook-server` dir
yarn start
```

Send a valid webhook that was signed for path `/hook/d7a2c49d-110a-4ed2-a07d-8fdb3ea6424b`.
```sh
curl -iX POST -H "Content-Type: application/json" \
-H "X-Tl-Webhook-Timestamp: 2022-03-11T14:00:33Z" \
-H "Tl-Signature: eyJhbGciOiJFUzUxMiIsImtpZCI6IjFmYzBlNTlmLWIzMzUtNDdjYS05OWE5LTczNzQ5NTc1NmE1OCIsInRsX3ZlcnNpb24iOiIyIiwidGxfaGVhZGVycyI6IngtdGwtd2ViaG9vay10aW1lc3RhbXAiLCJqa3UiOiJodHRwczovL3dlYmhvb2tzLnRydWVsYXllci5jb20vLndlbGwta25vd24vandrcyJ9..AE_QsBRhnsMkcRzd42wvY1e2HruUhkOgjuZKktGH_WmbD7rBzoaEHUuF36IxyyvCbLajd3MBExNmzjbrOQsGaspwAI5DcGVMFLKUhB7ZzUlTP9up3eNUrdwWyyfBWDQb-qmEuLnrhFDJvgCXEqlV5OLrt-O7LaRAJ4f9KHsZLQ_j2vPC" \
-d "{\"event_type\":\"payout_settled\",\"event_schema_version\":1,\"event_id\":\"8fb9fb4e-bb2b-400b-af64-59e5dde74bad\",\"event_body\":{\"transaction_id\":\"c34c8721-66a9-49f6-a229-284efcf88a02\",\"settled_at\":\"2022-03-11T14:00:32.933000Z\"}}" \
http://localhost:3000/hook/d7a2c49d-110a-4ed2-a07d-8fdb3ea6424b
```

Modifying the `X-Tl-Webhook-Timestamp` header, the body or the path will cause the above signature to be invalid.
79 changes: 79 additions & 0 deletions nodejs/examples/webhook-server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
const tlSigning = require("truelayer-signing");
const axios = require('axios');
const express = require('express');
const app = express();

const allowedJkus = {
"https://webhooks.truelayer.com/.well-known/jwks": true,
"https://webhooks.truelayer-sandbox.com/.well-known/jwks": true,
};

// global JWK cache
const cachedJwks = {};

// Tries to retrive the JWKs from a cache,
// otherwises, gets the JWKs from the endpoint.
// JWKs are unique by JKU+KID,
// which is how the cache is determined to be up to date
async function get_jwks(sig) {
let kid = tlSigning.extractKid(sig);
tlSigning.SignatureError.ensure(kid, `Tl-Signature has missing key id`);

let jku = tlSigning.extractJku(sig);
tlSigning.SignatureError.ensure(allowedJkus[jku], `Tl-Signature has invalid jku: ${jku}`);

// check if we have this KID/JKU pair stored
let jwks = cachedJwks[jku];
if (jwks) {
for (let i = 0; i < jwks.keys.length; i++) {
if (jwks.keys[i].kid == kid) {
return jwks;
}
}
}

// otherwise, fetch the JWKs from the server
cachedJwks[jku] = (await axios.get(jku)).data;
return cachedJwks[jku];
}

async function verify_hook(req) {
// extract the Tl-Signature from the headers
let sig = req.headers["tl-signature"];
tlSigning.SignatureError.ensure(sig, "missing Tl-Signature header");

// get the (cached) JWKs for this request
let jwks = await get_jwks(sig);

// verify the request (will throw on failure)
tlSigning.verify({
signature: sig,
method: req.method,
path: req.path,
headers: req.headers,
body: JSON.stringify(req.body),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm we shouldn't really be manipulating the body in any way before verifying

jwks: JSON.stringify(jwks),
});
}

// Note: Webhook path can be whatever is configured, here a unique path
// is used matching the README example signature.
app.post('/hook/d7a2c49d-110a-4ed2-a07d-8fdb3ea6424b',
express.json(), // parse body as json
(req, res, next) => {
// attempt to verify the webhook
// if success, call the next handler
// if failure, return 403 Forbidden
return verify_hook(req)
.then(next)
.catch(err => {
console.warn(err);
res.status(403).end();
});
},
(_req, res) => {
res.status(202).end();
}
);

app.listen(3000);
14 changes: 14 additions & 0 deletions nodejs/examples/webhook-server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "example-sign-request",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"axios": "^0.26.1",
"express": "^4.18.0",
"truelayer-signing": "file:../.."
},
"scripts": {
"start": "node index.js"
}
}
Loading