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

middy-recaptcha

v0.2.2

Published

reCAPTCHA validation Middy middleware for yours AWS Lambdas

Downloads

252

Readme

TypeScript

Version   License   GitHub issues by-label

🛵 What it does

Middy is a very simple middleware engine that allows you to simplify your AWS Lambda code when using Node.js. As I always had to implement and reimplement this type of logic, I decide to wrap up and give back tcommunity middleware for that validates a reCAPTCHA token in the body of a POST request.

If you are using Middy and have some public facing API you'll need more security (and believe me, better safe than sorry). This simple middleware will validate the token from reCAPTCHA v3.

🚀 Install

Use your favorite package manager:

yarn add middy-recaptcha
npm install middy-recaptcha -S

Usage

Besides @middy/core, you must also use @middy/http-json-body-parser since this middleware will read the request body and needed parsed as json.

To integrte with your frontend you just need to follow the guide from reCAPTCHA to rogrammatically invoke the challenge. The you need to pass the token generate in the body of your post request like this example:

const onSubmit = data => {
        setSubmited(true)
        window?.grecaptcha.ready(function() {
          window?.grecaptcha.execute('<Your public reCAPTCHA key>', {action: 'submit'}).then(function(token) {
            let payload = {
              token: token // In the current version, it must be sent in the body of the POST as token.
            }
            setPayload(JSON.stringify(payload, null, 2))
          });
        });
  };

In the folder backend you will find a CDK boilerplate to go up and running an HTTP API and in demo a simple NextJS example with the best react form lib[1]. These docs will be updated soon.

Canonical example, most secure

import middy from "@middy/core";
import cors from "@middy/http-cors";
import httpSecurityHeaders from "@middy/http-security-headers";
import jsonBodyParser from "@middy/http-json-body-parser";
import ssm from "@middy/ssm";
import reCAPTCHA from "middy-recaptcha";


import type {
  APIGatewayProxyEvent,
  APIGatewayProxyResult,
  Context,
} from "aws-lambda";

interface IReCAPTCHA extends Context {
  reCAPTCHA?: {
    success: boolean;
    challenge_ts: string;
    hostname: string;
    score: number;
    action: string;
  };
}

async function baseHandler(
  _event: APIGatewayProxyEvent,
  context: Context
): Promise<APIGatewayProxyResult> {
  const ctx: IReCAPTCHA = context;

  const message = {
    data: {
      message: "Hello from the other Side!",
      success: ctx?.reCAPTCHA?.success,
      score: ctx?.reCAPTCHA.score,
      challenge_ts: ctx?.reCAPTCHA?.challenge_ts,
      hostname: ctx?.reCAPTCHA?.hostname,
      action: ctx?.reCAPTCHA?.action,
    },
  };

  return {
    statusCode: 200,
    body: JSON.stringify(message, null, 2),
  };
}

let handler = middy(baseHandler);
handler
  .use(
    ssm({
      fetchData: {
        // the keys (`recaptchaSecret` and `recaptchaThreshold`) are the keys picked up in `context` by `reCAPTCHA()`, if specified
        recaptchaSecret: "/dev/recaptcha/secret",
        recaptchaThreshold: "/dev/recaptcha/threshold", // defaults to 0.8 if not specified
      },
      setToContext: true,
    })
  )
  .use(jsonBodyParser())
  .use(cors())
  .use(httpSecurityHeaders())
  .use(reCAPTCHA()); // Here goes our Middleware. 

export { handler };

Fast example, but not so best in security practices

// Everything the same, but you don't use "@middy/ssm" to fecth the secret key to validate in the backend your webapp, so it will need to pass the value as string as 'secret'. 
let handler = middy(baseHandler);
handler
  .use(
  .use(jsonBodyParser())
  .use(cors())
  .use(httpSecurityHeaders())
  .use(reCAPTCHA({
    secret: "<here goes your secret key>"
  })); // Here goes our Middleware.

export { handler };

With secretyou can load your secret key from an .env file or env parameters for your Lambda or hardcode the value. But, off course, none of us will ever do this kind of reckless nonsense.

Wink

Options

| Prop | Type | Description | |----------|:--------:|------------| | secret | string | Secret key from the reCAPTCHA admin. Highly recommend to use System Setting Manager.| | threshold | number | Default: 0.8 reCAPTCHA v3 returns a score (1.0 is very likely a good interaction, 0.0 is very likely a bot). Based on the score, you can take variable action in the context of your site. (Supports System Setting Manager via context) | | useIp | boolean | Default: false Optional. The user's IP address. | | tokenField | string | Default: token. The field on the event.body that has the reCaptcha token from your Frontend application. |

TODO

  • Improve docs. I want to do a write-up about the backend and frontend integration soon.

Thanks

All Middy contributors

See Also

📺 React Lite YouTube Embed: A private by default, faster and cleaner YouTube embed component for React applications

MIT License

Copyright (c) 2021 Ibrahim Cesar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


[1] In My Own Opinion®: React Hook Form