npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@truepic/webhook-verifier

v1.5.0

Published

Verify webhooks from Truepic Vision or Lens in your Node.js app

Downloads

277

Readme

This module verifies

  • the integrity of the data being received,
  • the authenticity of the sender (Truepic),
  • the authenticity of the receiver (you), and
  • the time between the request being sent and received to prevent replay attacks.

If you're not using Node.js, this also serves as a reference implementation with thorough documentation to make the translation into another language as painless as possible.

Installation

npm install @truepic/webhook-verifier

Usage

The @truepic/webhook-verifier module exports a default function that should be imported to begin:

import verifyTruepicWebhook from '@truepic/webhook-verifier'

CommonJS is also supported:

const verifyTruepicWebhook = require('@truepic/webhook-verifier')

This verifyTruepicWebhook function (or whatever you imported it as) is then called with the following arguments:

verifyTruepicWebhook({
  url: 'The full URL that received the request and is registered with Truepic.',
  secret: "The shared secret that's registered with Truepic.",
  header: 'The value of the `truepic-signature` header from the request.',
  body: 'The raw body (unparsed JSON) from the request.',
  leewayMinutes:
    'The number of minutes allowed between the request being sent and received. Defaults to `5`.',
})

A boolean true is returned if the webhook is verified in all of the ways described above. Otherwise, if anything fails to check out, a TruepicWebhookVerifierError is thrown with a message describing why (as much as possible).

You should place this function call at the beginning of your webhook route handler. Exactly how this is done depends on the web framework that you're using. Below are a few examples for popular web frameworks that should be easy to adapt if you're using a different one.

Example: Express.js

import verifyTruepicWebhook from '@truepic/webhook-verifier'
import express from 'express'
import { env } from 'node:process'

const app = express()

app.post(
  '/truepic/webhook',
  // This is important! We need the raw request body for `verifyTruepicWebhook`.
  express.raw({
    type: 'application/json',
  }),
  (req, res, next) => {
    try {
      verifyTruepicWebhook({
        url: env.TRUEPIC_WEBHOOK_URL,
        secret: env.TRUEPIC_WEBHOOK_SECRET,
        header: req.header('truepic-signature'),
        body: req.body.toString(),
      })
    } catch (error) {
      // The request cannot be verified. We're simply logging a warning here,
      // but you can handle however makes sense.
      console.warn(error)

      // Return OK so a (potential) bad actor doesn't gain any insight.
      return res.sendStatus(200)
    }

    // Process the webhook now that it's verified...

    res.sendStatus(200)
  },
)

// The rest of your app...

Example: Fastify

npm install fastify-raw-body
import verifyTruepicWebhook from '@truepic/webhook-verifier'
import Fastify from 'fastify'
import { env } from 'node:process'

const app = Fastify({
  logger: true,
})

// This is important! We need the raw request body for `verifyTruepicWebhook`.
await app.register(import('fastify-raw-body'))

app.post('/truepic/webhook', async (request) => {
  try {
    verifyTruepicWebhook({
      url: env.TRUEPIC_WEBHOOK_URL,
      secret: env.TRUEPIC_WEBHOOK_SECRET,
      header: request.headers['truepic-signature'],
      body: request.rawBody,
    })
  } catch (error) {
    // The request cannot be verified. We're simply logging a warning here,
    // but you can handle however makes sense.
    request.log.warn(error)

    // Return OK so a (potential) bad actor doesn't gain any insight.
    return {}
  }

  // Process the webhook now that it's verified...

  return {}
})

// The rest of your app...

Development

Prerequisites

The only prerequisite is a compatible version of Node.js (see engines.node in package.json).

Dependencies

Install dependencies with npm:

npm install

Tests

The built-in Node.js test runner and assertions module is used for testing.

To run the tests:

npm test

During development, it's recommended to run the tests automatically on file change:

npm test -- --watch

Docs

JSDoc is used to document the code.

To generate the docs as HTML to the (git-ignored) docs directory:

npm run docs

Code Style & Linting

Prettier is setup to enforce a consistent code style. It's highly recommended to add an integration to your editor that automatically formats on save.

ESLint is setup with the "recommended" rules to enforce a level of code quality. It's also highly recommended to add an integration to your editor that automatically formats on save.

To run via the command line:

npm run lint

Releasing

When the development branch is ready for release, Release It! is used to orchestrate the release process:

npm run release

Once the release process is complete, merge the development branch into the main branch, which should always reflect the latest release.