|
| 1 | +import axios from "axios" |
| 2 | +import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify" |
| 3 | +import { nanoid } from "nanoid" |
| 4 | +import { URLSearchParams } from "url" |
| 5 | + |
| 6 | +import { GitHubAccessToken, GitHubOrgMembership, GitHubUser, RoutePrams, Config, OAuthState } from "./types" |
| 7 | + |
| 8 | +export function registerGitHubOAuth(server: FastifyInstance, config: Config) { |
| 9 | + const secureCookies = !!process.env.VERCEL_URL |
| 10 | + |
| 11 | + const urls = { |
| 12 | + localAuthorize: "/login/oauth/authorize", |
| 13 | + githubAuthorize: "https://github.com/login/oauth/authorize", |
| 14 | + githubToken: "https://github.com/login/oauth/access_token", |
| 15 | + githubOrgMembers: `https://api.github.com/orgs/${config.githubOrgName}/members`, |
| 16 | + githubUserDetails: "https://api.github.com/user", |
| 17 | + } |
| 18 | + |
| 19 | + const cookieNames = { |
| 20 | + state: "state", |
| 21 | + user: "user", |
| 22 | + } as const |
| 23 | + |
| 24 | + const formatQueryParams = (params: NodeJS.Dict<string>) => { |
| 25 | + return "?" + new URLSearchParams(params).toString() |
| 26 | + } |
| 27 | + |
| 28 | + const unsignCookie = (res: FastifyReply, value: string) => { |
| 29 | + const unsigned = res.unsignCookie(value) |
| 30 | + |
| 31 | + if (unsigned.valid) { |
| 32 | + return JSON.parse(unsigned.value || "null") |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Make sure the authentication request was initiated by this application. |
| 38 | + */ |
| 39 | + const initiateOAuth = async (req: FastifyRequest, res: FastifyReply) => { |
| 40 | + const state: OAuthState = { |
| 41 | + randomToken: nanoid(), |
| 42 | + path: req.url, |
| 43 | + } |
| 44 | + |
| 45 | + res.clearCookie(cookieNames.user) |
| 46 | + res.setCookie(cookieNames.state, JSON.stringify(state), { |
| 47 | + httpOnly: true, |
| 48 | + maxAge: config.sessionDurationSeconds, |
| 49 | + path: "/", |
| 50 | + sameSite: "lax", |
| 51 | + secure: secureCookies, |
| 52 | + signed: true, |
| 53 | + }) |
| 54 | + res.redirect(302, urls.localAuthorize) |
| 55 | + } |
| 56 | + |
| 57 | + // |
| 58 | + // https://docs.github.com/en/free-pro-team@latest/developers/apps/authorizing-oauth-apps#web-application-flow |
| 59 | + // |
| 60 | + const redirectToGitHub = async (req: FastifyRequest<RoutePrams>, res: FastifyReply) => { |
| 61 | + const query = formatQueryParams({ |
| 62 | + client_id: config.githubClientId, |
| 63 | + scope: "read:user", |
| 64 | + state: req.cookies[cookieNames.state], |
| 65 | + }) |
| 66 | + res.redirect(302, urls.githubAuthorize + query) |
| 67 | + } |
| 68 | + |
| 69 | + const denyAccess = async (res: FastifyReply, message?: string) => { |
| 70 | + res.clearCookie(cookieNames.user) |
| 71 | + res.clearCookie(cookieNames.state) |
| 72 | + res.status(401).send({ |
| 73 | + statusCode: 401, |
| 74 | + error: "Unauthorized", |
| 75 | + message, |
| 76 | + }) |
| 77 | + } |
| 78 | + |
| 79 | + const getGitHubAccessToken = async (code: string): Promise<GitHubAccessToken> => { |
| 80 | + const url = urls.githubToken |
| 81 | + const headers = { |
| 82 | + Accept: "application/json", |
| 83 | + } |
| 84 | + const body = { |
| 85 | + client_id: config.githubClientId, |
| 86 | + client_secret: config.githubClientSecret, |
| 87 | + code, |
| 88 | + } |
| 89 | + |
| 90 | + const { data } = await axios.post<GitHubAccessToken>(url, body, { headers }) |
| 91 | + |
| 92 | + return data |
| 93 | + } |
| 94 | + |
| 95 | + const getGitHubUser = async (tokenData: GitHubAccessToken): Promise<GitHubUser> => { |
| 96 | + const url = urls.githubUserDetails |
| 97 | + const headers = { |
| 98 | + Accept: "application/json", |
| 99 | + Authorization: `${tokenData.token_type} ${tokenData.access_token}`, |
| 100 | + } |
| 101 | + |
| 102 | + const { data } = await axios.get<GitHubUser>(url, { headers }) |
| 103 | + |
| 104 | + return data |
| 105 | + } |
| 106 | + |
| 107 | + const getGitHubOrgMemberships = async (): Promise<GitHubOrgMembership[]> => { |
| 108 | + const url = urls.githubOrgMembers |
| 109 | + const headers = { |
| 110 | + Accept: "application/json", |
| 111 | + Authorization: `Bearer ${config.githubOrgAdminToken}`, |
| 112 | + } |
| 113 | + |
| 114 | + const { data } = await axios.get<GitHubOrgMembership[]>(url, { headers }) |
| 115 | + |
| 116 | + return data |
| 117 | + } |
| 118 | + |
| 119 | + const retrieveState = (req: FastifyRequest<RoutePrams>, res: FastifyReply) => { |
| 120 | + const state: OAuthState = unsignCookie(res, req.query.state || "") |
| 121 | + const expectedState: OAuthState = unsignCookie(res, req.cookies[cookieNames.state] || "") |
| 122 | + |
| 123 | + if (!state?.randomToken || state.randomToken !== expectedState?.randomToken) { |
| 124 | + throw new Error("State mismatch") |
| 125 | + } |
| 126 | + |
| 127 | + return state |
| 128 | + } |
| 129 | + |
| 130 | + const succeed = (res: FastifyReply, user: GitHubUser, path: string) => { |
| 131 | + res.setCookie(cookieNames.user, JSON.stringify(user), { |
| 132 | + httpOnly: false, |
| 133 | + maxAge: config.sessionDurationSeconds, |
| 134 | + path: "/", |
| 135 | + sameSite: "lax", |
| 136 | + secure: secureCookies, |
| 137 | + signed: false, |
| 138 | + }) |
| 139 | + res.redirect(302, path) |
| 140 | + } |
| 141 | + |
| 142 | + // |
| 143 | + // https://www.fastify.io/docs/latest/Hooks/ |
| 144 | + // |
| 145 | + server.addHook<RoutePrams>("preValidation", async (req, res) => { |
| 146 | + if (req.cookies[cookieNames.state] && req.cookies[cookieNames.user]) { |
| 147 | + return |
| 148 | + } |
| 149 | + |
| 150 | + if (req.url === urls.localAuthorize) { |
| 151 | + return redirectToGitHub(req, res) |
| 152 | + } |
| 153 | + |
| 154 | + const code = req.query.code |
| 155 | + |
| 156 | + if (!code) { |
| 157 | + return initiateOAuth(req, res) |
| 158 | + } |
| 159 | + |
| 160 | + try { |
| 161 | + const state = retrieveState(req, res) |
| 162 | + const tokenData = await getGitHubAccessToken(code) |
| 163 | + const user = await getGitHubUser(tokenData) |
| 164 | + const members = await getGitHubOrgMemberships() |
| 165 | + |
| 166 | + if (!members.find(member => member.id === user.id)) { |
| 167 | + return denyAccess(res, "It appears you are not a member of the required GitHub organization.") |
| 168 | + } |
| 169 | + |
| 170 | + return succeed(res, user, state.path) |
| 171 | + } catch (error) { |
| 172 | + console.error(error) |
| 173 | + return denyAccess(res, "It appears that the authentication request was initiated or processed incorrectly.") |
| 174 | + } |
| 175 | + }) |
| 176 | +} |
0 commit comments