• Stars
    star
    184
  • Rank 209,187 (Top 5 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 11 years ago
  • Updated 2 months ago

Reviews

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

Repository Details

Create and load persistent GitHub authentication tokens for command-line apps

ghauth

Create and load persistent GitHub authentication tokens for command-line apps

NPM

Important

Github deprecated their basic username/password auth api and have scheduled to sunset it November 13, 2020. ghauth v5.0.0+ supports the new device auth flow but requires some implementation changes and application registration with Github. Review the new API docs and see Setup for a simple upgrade guide between v4 and v5.

Example usage

const ghauth = require('ghauth')
const authOptions = {
  // provide a clientId from a Github oAuth application registration
  clientId: '123456',

  // awesome.json within the user's config directory will store the token
  configName: 'awesome',

  // (optional) whatever GitHub auth scopes you require
  scopes: [ 'user' ],

  // (optional)
  userAgent: 'My Awesome App'
}

const authData = await ghauth(authOptions)
console.log(authData)

// can also be run with a callback as:
//
// ghauth(authOptions, function (err, authData) {
//  console.log(authData)
// })

Will run something like this:

$ node awesome.js
  Authorize with GitHub by opening this URL in a browser:

    https://github.com/login/device

  and enter the following User Code:
  (or press ⏎ to enter a personal access token)

✔ Device flow complete.  Manage at https://github.com/settings/connections/applications/123456
✔ Authorized for rvagg
Wrote access token to "~/.config/awesome/config.json"
{
  token: '24d5dee258c64aef38a66c0c5eca459c379901c2',
  user: 'rvagg'
}

Because the token is persisted, the next time you run it there will be no prompts:

$ node awesome.js

{ user: 'rvagg',
  token: '24d5dee258c64aef38a66c0c5eca459c379901c2' }

When authUrl is configured for a Github enterprise endpoint, it will look more like this:

$ node awesome.js

GitHub username: rvagg
GitHub password: ✔✔✔✔✔✔✔✔✔✔✔✔
GitHub OTP (optional): 669684

{ user: 'rvagg',
  token: '24d5dee258c64aef38a66c0c5eca459c379901c2' }

API

ghauth(options, callback)

The options argument can have the following properties:

  • clientId (String, required unless noDeviceFlow is true): the clientId of your oAuth application on Github. See setup below for more info on creating a Github oAuth application.
  • configName (String, required unless noSave is true): the name of the config you are creating, this is required for saving a <configName>.json file into the users config directory with the token created. Note that the config directory is determined by application-config and is OS-specific.
  • noSave (Boolean, optional): if you don't want to persist the token to disk, set this to true but be aware that you will still be creating a saved token on GitHub that will need cleaning up if you are not persisting the token.
  • authUrl (String, optional): defaults to null since public Github no longer supports basic auth. Setting authUrl will allow you to perform basic authentication with a Github Enterprise instance. This setting is ignored if the host of the url is api.github.com or github.com.
  • promptName (String, optional): defaults to 'GitHub Enterprise', change this if you are prompting for GHE credentials. Not used for public GH authentication.
  • scopes (Array, optional): defaults to [], consult the GitHub scopes documentation to see what you may need for your application.
  • note (String, optional): defaults to 'Node.js command-line app with ghauth', override if you want to save a custom note with the GitHub token (user-visible). Only used with GHE basic authentication.
  • userAgent (String, optional): defaults to 'Magic Node.js application that does magic things with ghauth', only used for requests to GitHub, override if you have a good reason to do so.
  • passwordReplaceChar (String, optional): defaults to '✔', the character echoed when the user inputs their password. Can be set to '' to silence the output.
  • noDeviceFlow (Boolean, optional): disable the Device Flow authentication method. This will prompt users for a personal access token immediately if no existing configuration is found. Only applies when authUrl is not used.

The callback will be called with either an Error object describing what went wrong, or a data object as the second argument if the auth creation (or cache read) was successful. The shape of the second argument is { user:String, token:String }.

Setup

Github requires a clientId from a Github oAuth Application in order to complete oAuth device flow authentication.

  1. Register an "oAuth Application" with Github:
  1. Provide an application name, homepage URL and callback URL. You can make these two URLs the same, since your app will not be using a callback URL with the device flow.
  2. Go to your oAuth application's settings page and take note of the "Client ID" (this will get passed as clientId to ghauth). You can ignore the "Client Secret" value. It is not used.

The clientId is registered by the developer of the tool or CLI, and is baked into the code of your program. Users do not need to set this up, onyl the publisher of the app.

v4 to v5 Upgrade guide

  • A options.clientId is required to use device flow. Set up an oAuth application to get a clientId.
  • the options.authUrl now only applies to GitHub enterprise authentication which still only supports basic auth. Only pass this if you intend for GitHub Enterpise authentication.
  • options.note is only used for GHE basic auth now. Your oAuth application details serve the purpose of token note.
  • options.noDeviceFlow is available to skip the device flow if you are unable to create a clientId for some reason, and wish to skip to the personal access token input prompt immediately.

Contributing

ghauth is an OPEN Open Source Project. This means that:

Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.

See the CONTRIBUTING.md file for more details.

A note about tests

... there are no proper tests yet unfortunately. If you would like to contribute some that would be very helpful! We need to mock the GitHub API to properly test the functionality. Otherwise, testing of this library is done by its use downstream.

Contributors

ghauth is made possible by the excellent work of the following contributors:

Rod VaggGitHub/rvaggTwitter/@rvagg
Jeppe Nejsum MadsenGitHub/jeppenejsumTwitter/@nejsum
Max OgdenGitHub/maxogdenTwitter/@maxogden
Bret ComnesGitHub/bcomnesTwitter/@bcomnes

License & copyright

Copyright (c) 2014 ghauth contributors (listed above).

ghauth is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.

More Repositories

1

through2

Tiny wrapper around Node streams2 Transform to avoid explicit subclassing noise
JavaScript
1,894
star
2

node-worker-farm

Distribute processing tasks to child processes with an über-simple API and baked-in durability & custom concurrency options.
JavaScript
1,746
star
3

github-webhook-handler

Node.js web handler / middleware for processing GitHub Webhooks
JavaScript
783
star
4

bl

Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!
JavaScript
420
star
5

bole

A tiny JSON logger
JavaScript
265
star
6

nodei.co

nodei.co - Node.js badges, that's all
JavaScript
258
star
7

archived-morkdown

A simple Markdown editor
JavaScript
245
star
8

node-errno

libuv errno details exposed
JavaScript
244
star
9

archived-dnt

Docker Node Tester
Shell
222
star
10

archived-node-libssh

A Low-level Node.js binding for libssh
C++
132
star
11

archived-traversty

Headache-free DOM collection management and traversal
JavaScript
131
star
12

github-webhook

A flexible web server for reacting GitHub Webhooks
JavaScript
114
star
13

archived-node-pygmentize-bundled

A simple wrapper around Python's Pygments code formatter, with Pygments bundled
HTML
95
star
14

archived-lmdb

C++
85
star
15

jsonist

JSON over HTTP: A simple wrapper around hyperquest for dealing with JSON web APIs
JavaScript
66
star
16

isstream

Determine if an object is a Node.js Stream
JavaScript
63
star
17

polendina

Non-UI browser testing for JavaScript libraries from the command-line
JavaScript
63
star
18

archived-CAPSLOCKSCRIPT

JAVASCRIPT: T-H-E L-O-U-D P-A-R-T-S
JavaScript
60
star
19

archived-gfm2html

Convert a GitHub style Markdown file to HTML, complete with inline CSS
CSS
49
star
20

archived-node-level-session

A very fast and persistent web server session manager backed by LevelDB
JavaScript
49
star
21

cborg

fast CBOR with a focus on strictness
JavaScript
48
star
22

csv2

A Node Streams2 CSV parser
JavaScript
38
star
23

archived-pangyp

Node.js and io.js native addon build tool a (hopefully temporary) fork of TooTallNate/node-gyp
Python
38
star
24

archived-tsml

ES6 template string tag for multi-line cleaning - squash multi-line strings into a single line
JavaScript
37
star
25

archived-node-level-mapped-index

JavaScript
35
star
26

archived-node-rsz

An image resizer for Node.js
JavaScript
34
star
27

iamap

An Immutable Asynchronous Map
JavaScript
32
star
28

archived-servertest

A simple HTTP server testing tool
JavaScript
30
star
29

node-du

A simple JavaScript implementation of `du -sb`
JavaScript
29
star
30

rpi-newer-crosstools

Newer cross-compiler toolchains than are available @ https://github.com/raspberrypi/tools
C++
29
star
31

archived-node-brucedown

A near-perfect GitHub style Markdown to HTML converter
JavaScript
29
star
32

list-stream

Collect chunks / objects from a readable stream, write obejcts / chunks to a writable stream
JavaScript
27
star
33

archived-prr

JavaScript
26
star
34

archived-npm-explicit-deps

Say goodbye to fickle `~` and `^` semver ranges
JavaScript
26
star
35

ghissues

A node library to interact with the GitHub issues API
JavaScript
25
star
36

archived-string_decoder

Moved to https://github.com/nodejs/string_decoder
23
star
37

archived-node-sz

A Node.js utility for determining the dimensions of an image
JavaScript
23
star
38

js-ipld-hashmap

An associative array Map-type data structure for very large, distributed data sets built on IPLD
JavaScript
23
star
39

delayed

A collection of JavaScript helper functions for your functions, using setTimeout() to delay and defer.
JavaScript
22
star
40

archived-npm-publish-stream

A Node.js ReadableStream that emits data for each module published to npm
JavaScript
21
star
41

ghutils

A collection of utility functions for dealing with the GitHub API
JavaScript
20
star
42

archived-node-require-subvert

Yet another `require()` subversion library for mocking & stubbing
JavaScript
19
star
43

archived-level-ttl-cache

A pass-through cache for arbitrary objects or binary data using LevelDB, expired by a TTL
JavaScript
18
star
44

archived-level-spaces

Namespaced LevelUP instances
JavaScript
18
star
45

archived-node-generic-session

A generic web server session manager for use with any storage back-end
JavaScript
18
star
46

node-boganipsum

Node.js Lorem Ipsum ... Bogan Style!
JavaScript
17
star
47

archived-externr

Provide a plug-in mechanism for your JavaScript objects, exposing their inmost secrets
JavaScript
17
star
48

archived-npm-publish-notify

Desktop notifications on npm publish events
JavaScript
15
star
49

archived-new-contributors

Check a GitHub repository for new contributors
JavaScript
15
star
50

archived-blorg

Flexible static blog generator
JavaScript
15
star
51

archived-iojs-tools

A collection of utilities I use to help with managing io.js business
HTML
15
star
52

archived-node-simple-bufferstream

Turn a Node.js Buffer into a ReadableStream
JavaScript
14
star
53

archived-node-slow-stream

A throttleable stream, for working in the slow-lane
JavaScript
13
star
54

archived-node-crp

An image cropper for Node.js
JavaScript
13
star
55

archived-brtapsauce

Browserify TAP test runner for SauceLabs
JavaScript
12
star
56

npm-download-counts

Fetch package download counts for packages from the npm registry
JavaScript
12
star
57

archived-node-thmb

An image thumbnailer for Node.js
JavaScript
12
star
58

archived-nodei.co-chrome

Chrome extension to display nodei.co npm badges on GitHub README files for Node.js packages
JavaScript
11
star
59

ghrepos

A node library to interact with the GitHub repos API
JavaScript
11
star
60

archived-level-updown

LevelDOWN backed by LevelUP
JavaScript
11
star
61

archived-node-level-multiply

Make your LevelUP get(), put() and del() accept multiples keys & values.
JavaScript
11
star
62

ghteams

Node library to interact with the GitHub teams API
JavaScript
10
star
63

ghusers

A node library to interact with the GitHub users API
JavaScript
10
star
64

js-datastore-zipcar

An implementation of a Datastore (https://github.com/ipfs/interface-datastore) for IPLD blocks that operates on ZIP files
JavaScript
9
star
65

archived-bustermove

JavaScript
9
star
66

node-version-data

Load all Node.js and io.js versions and metadata about them
JavaScript
8
star
67

node-fd

File descriptor manager
JavaScript
8
star
68

archived-sanever

A saner semver parser
JavaScript
7
star
69

js-bitcoin-block

A Bitcoin block interface and decoder for JavaScript
JavaScript
7
star
70

ghpulls

A node library to interact with the GitHub pull requests API
JavaScript
7
star
71

testmark.js

Language-agnostic test fixtures in Markdown
JavaScript
6
star
72

campjs-2013-learn-you-node

CSS
5
star
73

archived-package-use

Use the nodei.co Node.js package download count API to create CSV data on package use
JavaScript
5
star
74

jsdoc4readme

Generate an API section for a README.md from inline JSDocs
JavaScript
5
star
75

archived-node-ssbl

Super-simple blog loader. Load markdown formatted blog files from a folder as a handy data structure for rendering
JavaScript
5
star
76

archived-quantities

JavaScript library for physical quantity representation and conversion
JavaScript
5
star
77

mkfiletree

Make a tree of files and directories by from data defined in an object
JavaScript
5
star
78

readfiletree

Deserialize an file/directory tree into object form
JavaScript
4
star
79

archived-check-python

Check for Python on the current system and return the value
JavaScript
4
star
80

archived-colors-tmpl

Simple templating for applying colors.js to strings
JavaScript
4
star
81

bit-sequence

Turn an arbitrary sequence of bits from a byte array and turn it into an integer
JavaScript
4
star
82

archived-node-downer-rangedel

A native LevelDOWN plugin providing a rangeDel() method
JavaScript
3
star
83

iavector

An Immutable Asynchronous Vector
JavaScript
3
star
84

blake2-node

Node.js BLAKE2 addon
C
3
star
85

js-ipld-schema-describer

Provide an object that suits the Data Model and get a naive IPLD Schema description of it.
JavaScript
3
star
86

nodei.co-pkginfo-api

API server to manage the npm package info data for nodei.co
JavaScript
3
star
87

bsplit2

A Node.js binary transform stream splitting chunks by newline characters
JavaScript
3
star
88

archived-npm-download-db

A local store containing npm download counts for all packages, able to provide rankings
JavaScript
3
star
89

gitexec

A specialised child process spawn for `git` commands
JavaScript
3
star
90

js-fil-utils

Miscellaneous JavaScript Filecoin proofs utilities
JavaScript
3
star
91

nodei.co-npm-dl-api

API server to manage the npm downloads counts and rankings for nodei.co
JavaScript
3
star
92

archived-kappa-bridge

A bridge for certificate-authenticated npm connections to Kappa registries
JavaScript
3
star
93

spacemon

Tool to monitor Filecoin storage space onboarding 🐶🍖
JavaScript
3
star
94

kasm

A WASM thing in Rust that's probably not what you're looking for
Rust
2
star
95

node-ci-containers

Dockerfile
2
star
96

r.va.gg

HTML
2
star
97

lxjs2013

JavaScript Databases II
CSS
2
star
98

archived-simpledb2level

Extract complete (or partial / incremental) SimpleDB data to a local LevelDB
JavaScript
2
star
99

js-bitcoin-extract

Tools to work with the Bitcoin blockchain (and IPLD)
JavaScript
2
star
100

js-ipld-vector

A JavaScript implementation of the IPLD Vetor specification
JavaScript
2
star