• Stars
    star
    360
  • Rank 117,262 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

😱 An easy, Ruby way to use the Pwned Passwords API.

Pwned

An easy, Ruby way to use the Pwned Passwords API.

Gem Version Build Status Maintainability Inline docs

API docs | GitHub repository

Table of Contents

About

Troy Hunt's Pwned Passwords API allows you to check if a password has been found in any of the huge data breaches.

Pwned is a Ruby library to use the Pwned Passwords API's k-Anonymity model to test a password against the API without sending the entire password to the service.

The data from this API is provided by Have I been pwned?. Before using the API, please check the acceptable uses and license of the API.

Here is a blog post I wrote on how to use this gem in your Ruby applications to make your users' passwords better.

Installation

Add this line to your application's Gemfile:

gem 'pwned'

And then execute:

$ bundle

Or install it yourself as:

$ gem install pwned

Usage

There are a few ways you can use this gem:

  1. Plain Ruby
  2. Rails
  3. Rails and Devise

Plain Ruby

To test a password against the API, instantiate a Pwned::Password object and then ask if it is pwned?.

password = Pwned::Password.new("password")
password.pwned?
#=> true
password.pwned_count
#=> 3303003

You can also check how many times the password appears in the dataset.

password = Pwned::Password.new("password")
password.pwned_count
#=> 3303003

Since you are likely using this as part of a sign-up flow, it is recommended that you rescue errors so if the service does go down, your user journey is not disturbed.

begin
  password = Pwned::Password.new("password")
  password.pwned?
rescue Pwned::Error => e
  # Ummm... don't worry about it, I guess?
end

Most of the times you only care if the password has been pwned before or not. You can use simplified accessors to check whether the password has been pwned, or how many times it was pwned:

Pwned.pwned?("password")
#=> true
Pwned.pwned_count("password")
#=> 3303003

Custom request options

You can set HTTP request options to be used with Net::HTTP.start when making the request to the API. These options are documented in the Net::HTTP.start documentation.

You can pass the options to the constructor:

password = Pwned::Password.new("password", read_timeout: 10)

You can also specify global defaults:

Pwned.default_request_options = { read_timeout: 10 }
HTTP Headers

The :headers option defines HTTP headers. These headers must be string keys.

password = Pwned::Password.new("password", headers: {
  'User-Agent' => 'Super fun new user agent'
})
HTTP Proxy

An HTTP proxy can be set using the http_proxy or HTTP_PROXY environment variable. This is the same way that Net::HTTP handles HTTP proxies if no proxy options are given. See URI::Generic#find_proxy for full details on how Ruby detects a proxy from the environment.

# Set in the environment
ENV["http_proxy"] = "https://username:[email protected]:12345"

# Will use the above proxy
password = Pwned::Password.new("password")

You can specify a custom HTTP proxy with the :proxy option:

password = Pwned::Password.new(
  "password",
  proxy: "https://username:[email protected]:12345"
)

If you don't want to set a proxy and you don't want a proxy to be inferred from the environment, set the :ignore_env_proxy key:

password = Pwned::Password.new("password", ignore_env_proxy: true)

ActiveRecord Validator

There is a custom validator available for your ActiveRecord models:

class User < ApplicationRecord
  validates :password, not_pwned: true
  # or
  validates :password, not_pwned: { message: "has been pwned %{count} times" }
end

I18n

You can change the error message using I18n (use %{count} to interpolate the number of times the password was seen in the data breaches):

en:
  errors:
    messages:
      not_pwned: has been pwned %{count} times
      pwned_error: might be pwned

Threshold

If you are ok with the password appearing a certain number of times before you decide it is invalid, you can set a threshold. The validator will check whether the pwned_count is greater than the threshold.

class User < ApplicationRecord
  # The record is marked as valid if the password has been used once in the breached data
  validates :password, not_pwned: { threshold: 1 }
end

Network Error Handling

By default the record will be treated as valid when we cannot reach the haveibeenpwned.com servers. This can be changed with the :on_error validator parameter:

class User < ApplicationRecord
  # The record is marked as valid on network errors.
  validates :password, not_pwned: true
  validates :password, not_pwned: { on_error: :valid }

  # The record is marked as invalid on network errors
  # (error message "could not be verified against the past data breaches".)
  validates :password, not_pwned: { on_error: :invalid }

  # The record is marked as invalid on network errors with custom error.
  validates :password, not_pwned: { on_error: :invalid, error_message: "might be pwned" }

  # We will raise an error on network errors.
  # This means that `record.valid?` will raise `Pwned::Error`.
  # Not recommended to use in production.
  validates :password, not_pwned: { on_error: :raise_error }

  # Call custom proc on error. For example, capture errors in Sentry,
  # but do not mark the record as invalid.
  validates :password, not_pwned: {
    on_error: ->(record, error) { Raven.capture_exception(error) }
  }
end

Custom Request Options

You can configure network requests made from the validator using :request_options (see Net::HTTP.start for the list of available options).

  validates :password, not_pwned: {
    request_options: {
      read_timeout: 5,
      open_timeout: 1
    }
  }

These options override the globally defined default options (see above).

In addition to these options, you can also set the following:

HTTP Headers

HTTP headers can be specified with the :headers key (e.g. "User-Agent")

  validates :password, not_pwned: {
    request_options: {
      headers: { "User-Agent" => "Super fun user agent" }
    }
  }
HTTP Proxy

An HTTP proxy can be set using the http_proxy or HTTP_PROXY environment variable. This is the same way that Net::HTTP handles HTTP proxies if no proxy options are given. See URI::Generic#find_proxy for full details on how Ruby detects a proxy from the environment.

  # Set in the environment
  ENV["http_proxy"] = "https://username:[email protected]:12345"

  validates :password, not_pwned: true

You can specify a custom HTTP proxy with the :proxy key:

  validates :password, not_pwned: {
    request_options: {
      proxy: "https://username:[email protected]:12345"
    }
  }

If you don't want to set a proxy and you don't want a proxy to be inferred from the environment, set the :ignore_env_proxy key:

  validates :password, not_pwned: {
    request_options: {
      ignore_env_proxy: true
    }
  }

Using Asynchronously

You may have a use case for hashing the password in advance, and then making the call to the Pwned Passwords API later (for example if you want to enqueue a job without storing the plaintext password). To do this, you can hash the password with the Pwned.hash_password method and then initialize the Pwned::HashedPassword class with the hash, like this:

hashed_password = Pwned.hash_password(password)
# some time later
Pwned::HashedPassword.new(hashed_password, request_options).pwned?

The Pwned::HashedPassword constructor takes all the same options as the regular Pwned::Password constructor.

Devise

If you are using Devise I recommend you use the devise-pwned_password extension which is now powered by this gem.

Rodauth

If you are using Rodauth then you can use the rodauth-pwned feature which is powered by this gem.

Command line

The gem provides a command line utility for checking passwords. You can call it from your terminal application like this:

$ pwned password
Pwned!
The password has been found in public breaches 3645804 times.

If you don't want the password you are checking to be visible, call:

$ pwned --secret

You will be prompted for the password, but it won't be displayed.

Unpwn

To cut down on unnecessary network requests, the unpwn project uses a list of the top one million passwords to check passwords against. Only if a password is not included in the top million is it then checked against the Pwned Passwords API.

How Pwned is Pi?

@daz shared a fantastic example of using this gem to show how many times the digits of Pi have been used as passwords and leaked.

require 'pwned'

PI = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111'

for n in 1..40
  password = Pwned::Password.new PI[0..(n + 1)]
  str = [ n.to_s.rjust(2) ]
  str << (password.pwned? ? '😑' : 'πŸ˜ƒ')
  str << password.pwned_count.to_s.rjust(4)
  str << password.password

  puts str.join ' '
end

The results may, or may not, surprise you.

 1 😑   16 3.1
 2 😑  238 3.14
 3 😑   34 3.141
 4 😑 1345 3.1415
 5 😑 2552 3.14159
 6 😑  791 3.141592
 7 😑 9582 3.1415926
 8 😑 1591 3.14159265
 9 😑  637 3.141592653
10 😑  873 3.1415926535
11 😑  137 3.14159265358
12 😑  103 3.141592653589
13 😑   65 3.1415926535897
14 😑  201 3.14159265358979
15 😑   41 3.141592653589793
16 😑   57 3.1415926535897932
17 😑   28 3.14159265358979323
18 😑   29 3.141592653589793238
19 😑    1 3.1415926535897932384
20 😑    7 3.14159265358979323846
21 😑    5 3.141592653589793238462
22 😑    2 3.1415926535897932384626
23 😑    2 3.14159265358979323846264
24 πŸ˜ƒ    0 3.141592653589793238462643
25 😑    3 3.1415926535897932384626433
26 πŸ˜ƒ    0 3.14159265358979323846264338
27 πŸ˜ƒ    0 3.141592653589793238462643383
28 πŸ˜ƒ    0 3.1415926535897932384626433832
29 πŸ˜ƒ    0 3.14159265358979323846264338327
30 πŸ˜ƒ    0 3.141592653589793238462643383279
31 πŸ˜ƒ    0 3.1415926535897932384626433832795
32 πŸ˜ƒ    0 3.14159265358979323846264338327950
33 πŸ˜ƒ    0 3.141592653589793238462643383279502
34 πŸ˜ƒ    0 3.1415926535897932384626433832795028
35 πŸ˜ƒ    0 3.14159265358979323846264338327950288
36 πŸ˜ƒ    0 3.141592653589793238462643383279502884
37 πŸ˜ƒ    0 3.1415926535897932384626433832795028841
38 πŸ˜ƒ    0 3.14159265358979323846264338327950288419
39 πŸ˜ƒ    0 3.141592653589793238462643383279502884197
40 πŸ˜ƒ    0 3.1415926535897932384626433832795028841971

Development

After checking out the repository, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/philnash/pwned. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Pwned project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

More Repositories

1

bitly

πŸ—œ A Ruby wrapper for the bit.ly API
Ruby
447
star
2

react-express-starter

A starter kit for React applications with a back end server all in the same project
JavaScript
179
star
3

react-web-audio

A small example React app that listens to the microphone and visualises the audio
JavaScript
163
star
4

mediadevices-camera-selection

πŸŽ₯ Examples on how to switch devices with the mediaDevices API
JavaScript
162
star
5

twilio-video-react-hooks

A video chat application built with Twilio Video and React Hooks
JavaScript
105
star
6

screen-capture

An exploration of screen capture in browsers.
JavaScript
103
star
7

ngrok-for-vscode

πŸš‡ A VSCode extension to control ngrok from the command palette
TypeScript
103
star
8

meta-spotify

[deprecated] A ruby wrapper for the Spotify Metadata API
Ruby
84
star
9

envyable

The simplest yaml to ENV config loader.
Ruby
76
star
10

sms-messages-app

A web powered SMS Messages app you can use with a Twilio number
CSS
69
star
11

web-assistant

A collection of experiments building towards a browser powered assistant
HTML
65
star
12

crotp

CrOTP - One Time Passwords for Crystal
Crystal
62
star
13

useful-twilio-functions

A set of useful Twilio Functions.
JavaScript
53
star
14

video-chat

An example of setting up basic video chat with WebRTC, node.js and Twilio
JavaScript
37
star
15

jekyll-gzip

Generate gzipped assets and files for your Jekyll site at build time
Ruby
35
star
16

react-twilio-phone

A Twilio Client based web phone, built with React
JavaScript
34
star
17

philna.sh

Phil Nash's personal site and blog
Astro
33
star
18

bulk-sms-alerts

An example of sending one, a few and many SMS messages using the Twilio APi
JavaScript
33
star
19

send-sms-react-twilio

An example React application that can send SMS messages via the Twilio API
JavaScript
32
star
20

react-programmable-chat

A React example of Twilio Programmable Chat
JavaScript
29
star
21

web-share-wrapper

A web component that wraps other share elements to replace with a web share button where supported.
JavaScript
22
star
22

twilio-video-svelte

A Twilio Video application built with Svelte
Svelte
21
star
23

whats_playing

Collaborative playlists over WhatsApp with Twilio and Spotify
Ruby
21
star
24

first-twilio-video-application

A demo of Twilio Video for the Build your first Twilio Video application webinar.
JavaScript
20
star
25

ruby-whatsapp-bots

A repo of WhatsApp bots built in Ruby
Ruby
19
star
26

ruby-google-sheets-sinatra

An example app using Ruby, Google Sheets and Sinatra
HTML
18
star
27

twiml_template

TwiML templates for Rails and Tilt.
Ruby
17
star
28

quote-bot

A bot built with Twilio SMS and Claudia Bot Builder
JavaScript
15
star
29

jekyll-brotli

Generate brotli compressed assets and files for your Jekyll site at build time
Ruby
15
star
30

twilio-chat-kendo-react

An example Twilio Programmable Chat application application using React and KendoReact Conversational UI
JavaScript
14
star
31

service-worker-background-fetch

A proof of concept of the background fetch API
HTML
12
star
32

guybot

A mighty pirate (and Twitter bot)
Ruby
12
star
33

jekyll-zopfli

Generate gzipped assets and files for your Jekyll site at build time using Zopfli compression
Ruby
12
star
34

ruby-quick-test

Run ruby test files quickly in Atom
CoffeeScript
12
star
35

jekyll-web_monetization

A Jekyll plugin to add Web Monetization API payment pointers to your site
Ruby
10
star
36

whatsapp-bot-capabilities

An example of a WhatsApp bot that can respond to location messages and can send images, vcards and location messages
JavaScript
9
star
37

pwned.js

An easy, promise based, way to test passwords securely against the Pwned Passwords API v2 in Node.js.
TypeScript
9
star
38

leap-motion-experiments

JavaScript
9
star
39

the-web-is-getting-pushy

An example of push notifications and service workers
JavaScript
9
star
40

web-monetization-components

A collection of web components you can use on your web monetized websites.
HTML
8
star
41

twilio-video-screen-sharing

JavaScript
8
star
42

community-sms-broadcast

An application that you can use to broadcast SMS messages to people listed on a Google Spreadsheet, powered by Twilio Functions and Twilio Programmable SMS
JavaScript
8
star
43

jsconf-schedule

An offline HTML schedule for JSConf EU
CSS
8
star
44

time-formatter

A web component that converts a date time into your user's time zone and formats it locally.
HTML
7
star
45

twilio-fax-ruby-sinatra

An application to send faxes with the Twilio Fax API
Ruby
7
star
46

jekyll-mastodon_webfinger

A Jekyll plugin that adds a WebFinger file to your site, allowing you to use your own domain to help others discover your Mastodon profile.
Ruby
7
star
47

twitter-sms

Send and receive tweets by SMS
Ruby
7
star
48

web-otp-input

A custom element to make it really easy to use the WebOTP API
JavaScript
6
star
49

super-secret-puppies

Ruby
6
star
50

tatooine

A Ruby interface to SWAPI (the Star Wars API).
Ruby
6
star
51

rails-phone-number-verification

An example application for verifying phone numbers in a Rails application.
Ruby
6
star
52

phism

A video collaboration app that we're building on Twitch: https://twitch.tv/phil_nash
JavaScript
5
star
53

whatrtc

WhatRTC? Everything you need to know to connect browsers to the world.
CSS
5
star
54

github-weekends

A silly browser extension that marks weekend contributions on GitHub's contribution graph in red
JavaScript
5
star
55

ship-it

Don't just comment, ship it.
JavaScript
5
star
56

envyable.cr

The simplest YAML to ENV config loader in Crystal
Crystal
5
star
57

fxrates-ios

A currency exchange rate calculator for iOS, written in Swift
Swift
4
star
58

sendgrid-email-status

A Rails application that sends emails via the SendGrid API and tracks their status
Ruby
4
star
59

getUserMedia

An example of using getUserMedia
JavaScript
4
star
60

twilio-video-chat-web-component

A Web Component version of Twilio Video [deprecated]
HTML
4
star
61

advent-of-code

Advent of Code 2017-2020 solutions in Crystal
Crystal
4
star
62

omg

Quick and dirty debugging any ruby!
Ruby
4
star
63

collabify

CSS
4
star
64

sms-bulb

HTML
4
star
65

celebrity-spotting

A Sinatra app that takes images from the Twilio API for WhatsApp and uses AWS Rekognition to spot celebrities
Ruby
4
star
66

ynfb

YNFB
Ruby
3
star
67

elixir-examples

Elixir
3
star
68

twiml_template_example

Examples on using the twiml_template gem
Ruby
3
star
69

contact-picker-twilio-client

A browser based phone that uses the Contact Picker API
JavaScript
3
star
70

fun-with-getusermedia

Fun with getUserMedia
JavaScript
2
star
71

exploring-amp-email

A collection of projects implementing AMP email with SendGrid
JavaScript
2
star
72

hubot-twilio-ip-messaging

A Hubot adapter for Twilio IP Messaging
CoffeeScript
2
star
73

four-steps-from-javascript-to-typescript

JavaScript
2
star
74

thereminjs

JavaScript
2
star
75

philnash

philnash/philnash is philnash's repo about philnash
JavaScript
2
star
76

jira-twilio-plugins

HTML
2
star
77

twilio-client-and-accessibility

Exploring accessiblity and Twilio Client
Ruby
2
star
78

superclass-twilio-video-demo

A demo of Twilio Video for Superclass 2019
JavaScript
2
star
79

ng-sms-messages

An SMS application for Twilio, written with Angular and Service Workers
TypeScript
2
star
80

video-collaboration

An application using Twilio Video implementing various collaboration features
JavaScript
2
star
81

advanced-twilio-video

An example of using some advanced Twilio Video features to improve the user experience
JavaScript
2
star
82

twilio-liftoff

The example code for the Twilio Liftoff webinar series
JavaScript
2
star
83

sms-messages-hanami

An example application for receiving and responding to SMS messages from Twilio in Hanami
Ruby
2
star
84

pirate-api

πŸ΄β€β˜ οΈ An API wrapper for translating from English to Pirate and generating pirate insults ☠️
TypeScript
2
star
85

worlds-worst-synth

The world's worst synth
JavaScript
2
star
86

dad-jokes-cli

A CLI for getting Dad Jokes
JavaScript
1
star
87

twilio-typescript-examples

Examples of using Twilio with TypeScript
TypeScript
1
star
88

crystal-experiments

Crystal Experiments with the Twilio API
Crystal
1
star
89

install-service-worker

Three different ways to install a service worker
HTML
1
star
90

WindowSize

A bookmarklet to get the current height and width of the viewport
JavaScript
1
star
91

todomvc-indexeddb

A vanilla JS implementation of TodoMVC with an IndexedDB data store
JavaScript
1
star
92

Sheenboard

1
star
93

bluemix-twilio-alchemy

HTML
1
star
94

discogs-scanner

A web app to scan records and add them to your Discogs collection
Svelte
1
star
95

twilio-autopilot-competition-entry-bot

The back-end Twilio Functions for a Twilio Autopilot bot that asks questions and enters people into a competition
JavaScript
1
star
96

rainbow

A silly demo of device orientation events
1
star
97

taskrouter_priority

A priority call centre built with Twilio TaskRouter
Ruby
1
star
98

asst

A command line interface for OpenAI's ChatGPT written in JavaScript
JavaScript
1
star
99

growler_alerts_starter

HTML
1
star
100

simulring-control

A Twilio Function that pulls and filters numbers from a Google Sheet to be used in a Studio Flow
JavaScript
1
star