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

@bogeychan/elysia-oauth2

v0.0.21

Published

A plugin for Elysia.js for server-side OAuth 2.0 Authorization Code Flow

Downloads

277

Readme

@bogeychan/elysia-oauth2

A plugin for Elysia.js for server-side OAuth 2.0 Authorization Code Flow

Migration guide

Installation

bun add @bogeychan/elysia-oauth2

Usage

import { Elysia } from 'elysia'
import oauth2, { github } from '@bogeychan/elysia-oauth2'

import { randomBytes } from 'crypto'

const globalState = randomBytes(8).toString('hex')
let globalToken = null

const app = new Elysia()

const auth = oauth2({
	profiles: {
		// define multiple OAuth 2.0 profiles
		github: {
			provider: github(),
			scope: ['user']
		}
	},
	state: {
		// custom state verification between requests
		check(ctx, name, state) {
			return state === globalState
		},
		generate(ctx, name) {
			return globalState
		}
	},
	storage: {
		// storage of users' access tokens is up to you
		get(ctx, name) {
			return globalToken
		},
		set(ctx, name, token) {
			globalToken = token
		},
		delete(ctx, name) {
			globalToken = null
		}
	}
})

function userPage(user: {}, logout: string) {
	const html = `<!DOCTYPE html>
    <html lang="en">
    <body>
      User:
      <pre>${JSON.stringify(user, null, '\t')}</pre>
      <a href="${logout}">Logout</a>
    </body>
    </html>`

	return new Response(html, { headers: { 'Content-Type': 'text/html' } })
}

app
	.use(auth)
	.get('/', async (ctx) => {
		// get login, callback, logout urls for one or more OAuth 2.0 profiles
		const profiles = ctx.profiles('github')

		// check if one or more OAuth 2.0 profiles are authorized
		if (await ctx.authorized('github')) {
			const user = await fetch('https://api.github.com/user', {
				// ... and use the Authorization header afterwards
				headers: await ctx.tokenHeaders('github')
			})

			return userPage(await user.json(), profiles.github.logout)
		}

		// Render login page
		const html = `<!DOCTYPE html>
    <html lang="en">
    <body>
      <h2>Login with <a href="${profiles.github.login}">Github</a></h2>
    </body>
    </html>`

		return new Response(html, { headers: { 'Content-Type': 'text/html' } })
	})
	.listen(3000)

console.log('Listening on http://localhost:3000')

Where are the client credentials?

  1. Generate a client id and client secret for an OAuth app on Github

  2. Use http://localhost:3000/login/github/authorized as your Authorization callback URL

  3. Create an .env file based on the previously generated client credentials:

    GITHUB_OAUTH_CLIENT_ID=client id
    GITHUB_OAUTH_CLIENT_SECRET=client secret
  4. Bun automatically loads environment variables from .env files

If you are unsure which URL should be used as Authorization callback URL call ctx.profiles() without an argument to get all URLs of all registered OAuth 2.0 Profiles:

app
	.use(auth)
	.get('/', (ctx) => {
		return ctx.profiles()
	})
	.listen(3000)

Use custom plugins in Storage and State

import oauth2, {
	github,
	type InferContext,
	type TOAuth2AccessToken
} from '@bogeychan/elysia-oauth2'

const mySessionPLugin = new Elysia().derive((ctx) => ({
	session: {
		getOAuthToken(name: string): TOAuth2AccessToken {
			const sessionId = ctx.cookie['session-id'].value
			return // TODO
		},
		setOAuthToken(name: string, token: TOAuth2AccessToken) {
			// TODO
		},
		deleteOAuthToken(name: string) {
			// TODO
		}
	}
}))

const app = new Elysia().use(mySessionPLugin)

const auth = oauth2({
	profiles: {
		github: {
			provider: github(),
			scope: ['user']
		}
	},
	state: {
		check(ctx, name, state) {
			return state === globalState
		},
		generate(ctx, name) {
			return globalState
		}
	},
	storage: {
		get(ctx: InferContext<typeof app>, name) {
			return ctx.session.getOAuthToken(name)
		},
		set(ctx: InferContext<typeof app>, name, token) {
			ctx.session.setOAuthToken(name, token)
		},
		delete(ctx: InferContext<typeof app>, name) {
			ctx.session.deleteOAuthToken(name)
		}
	}
})

Use predefined OAuth 2.0 providers

import { azure, discord, github, ... } from '@bogeychan/elysia-oauth2';

Define your own OAuth 2.0 provider

import oauth2, { TOAuth2Provider } from '@bogeychan/elysia-oauth2'

function myGithub(): TOAuth2Provider {
	return {
		clientId: 'YOUR_CLIENT_ID',
		clientSecret: 'YOUR_CLIENT_SECRET',

		auth: {
			url: 'https://github.com/login/oauth/authorize',
			params: {
				allow_signup: true
			}
		},

		token: {
			url: 'https://github.com/login/oauth/access_token',
			params: {}
		}
	}
}

const auth = oauth2({
	profiles: {
		github: {
			provider: myGithub(),
			scope: ['user']
		}
	}
	// ...
})

License

MIT