Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Add GH [WIP]

Tomas Valenta8243f9d0677a
diff --git a/components/Repos.tsx b/components/Repos.tsx
new file mode 100644
index 000000000..d44179289
--- /dev/null
+++ b/components/Repos.tsx
@@ -0,0 +1,191 @@
+import React, { useCallback, useMemo, useState } from 'react'
+import { GithubIcon, SearchIcon } from 'lucide-react'
+import clsx from 'clsx'
+import Fuse from 'fuse.js'
+
+import { useGitHub } from 'hooks/useGitHub'
+import useListenMessage from 'hooks/useListenMessage'
+import Button from 'components/Button'
+import Text from 'components/Text'
+import { useLocalStorage } from 'hooks/useLocalStorage'
+import { useRepositories } from 'hooks/useRepositories'
+import { PostProjectBody } from 'pages/api/project'
+import { openPopupModal } from 'utils/popupModal'
+import TitleButton from 'components/TitleButton'
+import Input from 'components/Input'
+import SpinnerIcon from 'components/Spinner'
+
+export interface Props {
+ onRepoSelection: (repoSetup: Pick<PostProjectBody, 'accessToken' | 'installationID' | 'repositoryID'> & { fullName: string, defaultBranch: string, branches?: string[], url: string }) => void
+}
+
+function Repos({ onRepoSelection }: Props) {
+ const [accessToken, setAccessToken] = useLocalStorage<string | undefined>('gh_access_token', undefined)
+ const gitHub = useGitHub(accessToken)
+ const { repos, refetch } = useRepositories(gitHub)
+ const [query, setQuery] = useState<string>()
+
+ const searchEngine = useMemo(() => {
+ if (!repos) return
+ return new Fuse(repos, {
+ keys: ['full_name'],
+ threshold: 0.4,
+ })
+ }, [repos])
+
+ const filteredRepos = query && searchEngine ? searchEngine.search(query).map(i => i.item) : repos || []
+
+ const handleEvent = useCallback((event: MessageEvent) => {
+ if (event.data.accessToken) {
+ setAccessToken(event.data.accessToken)
+ } else if (event.data.installationID) {
+ refetch()
+ }
+ }, [setAccessToken, refetch])
+ useListenMessage(handleEvent)
+
+ async function selectRepository(r: Pick<PostProjectBody, 'installationID' | 'repositoryID'> & { fullName: string, defaultBranch: string, url: string }) {
+ if (!accessToken) return
+ onRepoSelection({
+ ...r,
+ accessToken,
+ branches: [r.defaultBranch],
+ })
+
+ const [repositoryOwnerName, repositoryName] = r.fullName.split('/')
+ const repoBranches = await gitHub?.repos.listBranches({
+ owner: repositoryOwnerName,
+ repo: repositoryName,
+ })
+
+ const branches = repoBranches?.data.map(b => b.name)
+ onRepoSelection({
+ ...r,
+ branches,
+ accessToken,
+ })
+ }
+
+ async function signWithGitHubOAuth() {
+ const url = new URL('/login/oauth/authorize', 'https://github.com')
+ url.searchParams.set('client_id', process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID!)
+ openPopupModal(url)
+ }
+
+ function configureGitHubApp() {
+ const url = new URL('https://github.com/apps/devbook-for-github/installations/new')
+ openPopupModal(url)
+ }
+
+ return (
+ <div className="flex flex-1 flex-col space-y-2 overflow-hidden">
+ <div className={clsx(`
+ border
+ overflow-hidden
+ rounded
+ flex
+ flex-col
+ flex-1`,
+ { 'bg-white': accessToken },
+ )}>
+ {!accessToken &&
+ <div className="flex flex-1 justify-center items-center">
+ <Button
+ variant={Button.variant.Full}
+ onClick={signWithGitHubOAuth}
+ text="Connect GitHub"
+ icon={<GithubIcon />}
+ />
+ </div>
+ }
+
+ {accessToken &&
+ <div className="flex overflow-hidden flex-col flex-1">
+ <div className="flex items-center space-x-2 border-b px-8 py-4">
+ <SearchIcon size="16px" />
+ <Input
+ placeholder="Search repositories..."
+ value={query}
+ onChange={q => setQuery(q)}
+ autofocus
+ />
+ </div>
+
+
+ {!repos &&
+ <div className="flex flex-1 items-center justify-center flex-col space-y-1 text-slate-500">
+ <SpinnerIcon className="text-slate-400" />
+ <Text text="Fetching repositories" />
+ </div>
+ }
+
+ {repos && repos.length === 0 &&
+ <div className="flex flex-1 items-center justify-center">
+ <Text text="No connected repositories found" />
+ <Button
+ variant={Button.variant.Full}
+ onClick={configureGitHubApp}
+ text="Configure permissions"
+ icon={<GithubIcon />}
+ />
+ </div>
+ }
+
+ {repos && repos.length > 0 &&
+ <div className="
+ flex
+ flex-col
+ scroller
+ overflow-auto
+ pl-8
+ flex-1
+ pr-6
+ ">
+ {filteredRepos.map(r => (
+ <div
+ className={clsx(
+ 'flex',
+ 'justify-between',
+ 'py-4',
+ 'border-b',
+ )}
+ key={r.id}
+ >
+ <div className="flex items-center space-x-2">
+ <GithubIcon size="16px" />
+ <Text text={r.full_name} className="" />
+ </div>
+ <Button
+ onClick={() => selectRepository({
+ defaultBranch: r.default_branch,
+ installationID: r.installation_id,
+ repositoryID: r.id,
+ fullName: r.full_name,
+ url: r.html_url,
+ })}
+ text="Select"
+ />
+ </div>
+ ))}
+ </div>
+ }
+ </div>
+ }
+ </div>
+ {accessToken &&
+ <div className="flex justify-between">
+ <TitleButton
+ onClick={signWithGitHubOAuth}
+ text="Reauthenticate GitHub Account"
+ />
+ <TitleButton
+ onClick={configureGitHubApp}
+ text="Configure GitHub App"
+ />
+ </div>
+ }
+ </div>
+ )
+}
+
+export default Repos
diff --git a/components/TitleButton.tsx b/components/TitleButton.tsx
new file mode 100644
index 000000000..8e5f2129d
--- /dev/null
+++ b/components/TitleButton.tsx
@@ -0,0 +1,26 @@
+import clsx from 'clsx'
+
+import Text from 'components/Text'
+
+export interface Props {
+ onClick: () => void
+ text: string
+}
+
+function TitleButton({ onClick, text }: Props) {
+ return (
+ <Text
+ size={Text.size.S3}
+ onClick={onClick}
+ text={text}
+ className={clsx(
+ 'whitespace-nowrap',
+ 'cursor-pointer',
+ 'transition-all',
+ 'text-slate-400 hover:text-green-800',
+ )}
+ />
+ )
+}
+
+export default TitleButton
diff --git a/github/installationClient.ts b/github/installationClient.ts
new file mode 100644
index 000000000..b57ea2174
--- /dev/null
+++ b/github/installationClient.ts
@@ -0,0 +1,17 @@
+import { Octokit } from '@octokit/rest'
+import { createAppAuth } from '@octokit/auth-app'
+
+function getInstallationClient({ installationID: installationId }: { installationID: number }) {
+ const appId = process.env.GITHUB_APP_ID
+ const privateKey = process.env.GITHUB_APP_PRIVATE_KEY
+ return new Octokit({
+ authStrategy: createAppAuth,
+ auth: {
+ privateKey,
+ appId,
+ installationId,
+ },
+ })
+}
+
+export default getInstallationClient
diff --git a/github/repoProcessing.ts b/github/repoProcessing.ts
new file mode 100644
index 000000000..68946548a
--- /dev/null
+++ b/github/repoProcessing.ts
@@ -0,0 +1,95 @@
+import { Octokit } from '@octokit/rest'
+// import * as toml from '@iarna/toml'
+import JSZip from 'jszip'
+
+import path from 'path'
+
+// const envConfigName = 'dbk.toml'
+
+export type AppContentJSON = {
+ env?: {
+ id: string,
+ }
+ mdx: {
+ name: string
+ content: string
+ }[]
+ css?: {
+ name: string
+ content: string
+ }[]
+}
+
+export interface File {
+ content: string
+ name: string
+}
+
+export interface EnvConfig {
+ id: string
+}
+
+export async function getRepo({
+ owner,
+ repo,
+ ref,
+ github,
+}: {
+ owner: string,
+ repo: string,
+ ref: string,
+ github: Octokit,
+}) {
+ const archive = await github.repos.downloadZipballArchive({
+ accept: 'application/vnd.github+json',
+ owner,
+ repo,
+ ref,
+ })
+
+ const zip = JSZip()
+ await zip.loadAsync(archive.data as string)
+ return zip
+}
+
+export async function getAppContentFromRepo({
+ dir,
+ repo,
+}: {
+ repo: JSZip,
+ dir: string,
+}): Promise<AppContentJSON | undefined> {
+ const rootRegex = dir === '.' || dir === './' ? new RegExp('^[^\/]+\/$') : new RegExp(`^[^\/]+\/${dir}\/$`)
+ const rootDir = repo.folder(rootRegex)
+
+ if (rootDir.length === 0) return
+ const name = rootDir[0].name
+ const root = repo.folder(name)
+
+ if (!root) return
+
+ // const envConfigContentRaw = await root.file(envConfigName)?.async('string')
+ // if (!envConfigContentRaw) {
+ // throw new Error(`Invalid env config in ${name}`)
+ // }
+ // const env = toml.parse(envConfigContentRaw) as unknown as EnvConfig
+ const mdx = await Promise.all(root.file(/.+.mdx$/).map(f => getFile(f, dir)))
+ const css = await Promise.all(root.file(/.+.css$/).map(f => getFile(f, dir)))
+
+ return {
+ // env,
+ css,
+ mdx,
+ }
+}
+
+async function getFile(o: JSZip.JSZipObject | null, root: string): Promise<File> {
+ if (!o) {
+ throw new Error('Cannot get file')
+ }
+
+ return {
+ name: path.relative(root, o.name.split('/').slice(1).join('/')),
+ content: await o.async('string')
+ }
+}
diff --git a/github/userClient.ts b/github/userClient.ts
new file mode 100644
index 000000000..3474a0ae7
--- /dev/null
+++ b/github/userClient.ts
@@ -0,0 +1,11 @@
+import { Octokit } from '@octokit/rest'
+
+function getUserClient({ accessToken }: { accessToken: string }) {
+ return new Octokit({
+ auth: accessToken,
+ })
+}
+
+export type GitHubUserClient = ReturnType<typeof getUserClient>
+
+export default getUserClient
diff --git a/github/webhooks.ts b/github/webhooks.ts
new file mode 100644
index 000000000..868343338
--- /dev/null
+++ b/github/webhooks.ts
@@ -0,0 +1,104 @@
+import type { HandlerFunction } from '@octokit/webhooks/dist-types/types'
+import {
+ Webhooks,
+ createNodeMiddleware,
+} from '@octokit/webhooks'
+import { apps_content, apps } from 'database'
+
+import { getAppContentFromRepo, getRepo } from './repoProcessing'
+import { prisma } from 'queries/prisma'
+import getClient from './installationClient'
+
+export const branchRefPrefix = 'refs/heads/'
+
+export async function getGitHubWebhooksMiddleware() {
+ const webhooks = new Webhooks({
+ secret: process.env.GITHUB_APP_WEBHOOK_SECRET!,
+ })
+ webhooks.on('push', pushHandler)
+ return createNodeMiddleware(webhooks, { path: '/api/github/webhook' })
+}
+
+export async function deployLatestRepoState({
+ repositoryFullName,
+ installationID,
+ apps,
+ branch,
+}: {
+ repositoryFullName: string,
+ installationID: number,
+ branch: string,
+ apps: Pick<apps, 'repository_path' | 'id'>[],
+}) {
+ const [repositoryOwnerName, repositoryName] = repositoryFullName.split('/')
+
+ if (!installationID) {
+ throw new Error('InstallationID not found')
+ }
+
+ const github = getClient({ installationID })
+ const repo = await getRepo({
+ github,
+ repo: repositoryName,
+ owner: repositoryOwnerName,
+ ref: `${branchRefPrefix}${branch}`,
+ })
+
+ await Promise.all(apps.map(async app => {
+ try {
+ const content = await getAppContentFromRepo({
+ dir: app.repository_path,
+ repo,
+ })
+
+ if (!content) throw new Error('No content found in the repo')
+
+ await prisma.apps_content.upsert({
+ create: {
+ content: content as unknown as NonNullable<apps_content['content']>,
+ app_id: app.id,
+ },
+ update: {
+ content: content as unknown as NonNullable<apps_content['content']>,
+ updated_at: new Date(),
+ },
+ where: {
+ app_id: app.id,
+ }
+ })
+ } catch (err) {
+ console.error(`Error deploying app "${app.id}" content from repository "${repositoryFullName}"`, err)
+ }
+ }))
+}
+
+const pushHandler: HandlerFunction<'push', unknown> = async (event) => {
+ const { payload } = event
+ const installationID = payload.installation?.id
+ const repositoryID = payload.repository.id
+ const branch = payload.ref.slice(branchRefPrefix.length)
+
+ if (!installationID) {
+ throw new Error('InstallationID not found')
+ }
+
+ const apps = await prisma.apps.findMany({
+ where: {
+ repository_branch: {
+ equals: branch,
+ },
+ github_repositories: {
+ repository_id: repositoryID,
+ },
+ },
+ })
+
+ if (apps.length === 0) return
+
+ await deployLatestRepoState({
+ apps,
+ branch,
+ installationID,
+ repositoryFullName: payload.repository.full_name,
+ })
+}
diff --git a/hooks/useGitHub.ts b/hooks/useGitHub.ts
new file mode 100644
index 000000000..1e97f7043
--- /dev/null
+++ b/hooks/useGitHub.ts
@@ -0,0 +1,14 @@
+import { useEffect, useState } from 'react'
+
+import getUserClient, { GitHubUserClient } from 'github/userClient'
+
+export function useGitHub(accessToken?: string) {
+ const [gitHub, setGitHub] = useState<GitHubUserClient>()
+
+ useEffect(function init() {
+ if (!accessToken) return
+ setGitHub(getUserClient({ accessToken }))
+ }, [accessToken])
+
+ return gitHub
+}
diff --git a/hooks/useListenMessage.ts b/hooks/useListenMessage.ts
new file mode 100644
index 000000000..d7b285617
--- /dev/null
+++ b/hooks/useListenMessage.ts
@@ -0,0 +1,14 @@
+import {
+ useEffect,
+} from 'react'
+
+function useListenMessage(callback: (event: MessageEvent<any>) => void) {
+ useEffect(function register() {
+ window.addEventListener('message', callback)
+ return () => {
+ window.removeEventListener('message', callback)
+ }
+ }, [callback])
+}
+
+export default useListenMessage
diff --git a/hooks/useLocalStorage.ts b/hooks/useLocalStorage.ts
new file mode 100644
index 000000000..6f0495a94
--- /dev/null
+++ b/hooks/useLocalStorage.ts
@@ -0,0 +1,40 @@
+import { useState } from 'react'
+
+export function useLocalStorage<T>(key: string, initialValue: T) {
+ // State to store our value
+ // Pass initial state function to useState so logic is only executed once
+ const [storedValue, setStoredValue] = useState<T>(() => {
+ if (typeof window === 'undefined') {
+ return initialValue
+ }
+ try {
+ // Get from local storage by key
+ const item = window.localStorage.getItem(key)
+ // Parse stored json or if none return initialValue
+ return item ? JSON.parse(item) : initialValue
+ } catch (error) {
+ // If error also return initialValue
+ console.log(error)
+ return initialValue
+ }
+ })
+ // Return a wrapped version of useState's setter function that ...
+ // ... persists the new value to localStorage.
+ const setValue = (value: T | ((val: T) => T)) => {
+ try {
+ // Allow value to be a function so we have same API as useState
+ const valueToStore =
+ value instanceof Function ? value(storedValue) : value
+ // Save state
+ setStoredValue(valueToStore)
+ // Save to local storage
+ if (typeof window !== 'undefined') {
+ window.localStorage.setItem(key, JSON.stringify(valueToStore))
+ }
+ } catch (error) {
+ // A more advanced implementation would handle the error case
+ console.log(error)
+ }
+ }
+ return [storedValue, setValue] as const
+}
diff --git a/hooks/useRepositories.ts b/hooks/useRepositories.ts
new file mode 100644
index 000000000..eca5a0748
--- /dev/null
+++ b/hooks/useRepositories.ts
@@ -0,0 +1,42 @@
+import { useEffect, useReducer, useState } from 'react'
+
+import { GitHubUserClient } from 'github/userClient'
+
+async function fetchRepos(client: GitHubUserClient) {
+ const installations = await client.apps.listInstallationsForAuthenticatedUser()
+
+ const repos = await Promise.all(
+ installations.data.installations.map(async i => {
+ const repos = await client.apps.listInstallationReposForAuthenticatedUser({
+ installation_id: i.id,
+ // TODO: Add pagination so we fetch all the repos not just the first 100
+ per_page: 100,
+ headers: {
+ // We have to manually circumvent the caching mechanism here.
+ // This request is called only when the user changes or when the component mounts, so we don't exceed the GitHub API quotas.
+ 'If-Modified-Since': 'Sun, 14 Nov 2021 13:42:15 GMT',
+ },
+ })
+ return repos.data.repositories.map(r => ({
+ ...r,
+ installation_id: i.id,
+ }))
+ })
+ )
+ return repos.flat()
+}
+
+export function useRepositories(client?: GitHubUserClient) {
+ const [repos, setRepos] = useState<Awaited<ReturnType<typeof fetchRepos>>>()
+ const [hook, refetch] = useReducer(() => ({}), {})
+
+ useEffect(function fetch() {
+ if (!client) return
+ fetchRepos(client).then(setRepos)
+ }, [client, hook])
+
+ return {
+ repos,
+ refetch,
+ }
+}
diff --git a/package-lock.json b/package-lock.json
index ad3ddfbc3..bbce62ac6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,6 +10,9 @@
"hasInstallScript": true,
"dependencies": {
"@devbookhq/splitter": "^1.4.0",
+ "@octokit/auth-app": "^4.0.13",
+ "@octokit/rest": "^19.0.11",
+ "@octokit/webhooks": "^11.0.0",
"@prisma/client": "^4.13.0",
"@supabase/auth-helpers-nextjs": "^0.5.5",
"@supabase/auth-helpers-react": "^0.3.1",
@@ -462,6 +465,299 @@
"node": ">= 8"
}
},
+ "node_modules/@octokit/auth-app": {
+ "version": "4.0.13",
+ "resolved": "https://registry.npmjs.org/@octokit/auth-app/-/auth-app-4.0.13.tgz",
+ "integrity": "sha512-NBQkmR/Zsc+8fWcVIFrwDgNXS7f4XDrkd9LHdi9DPQw1NdGHLviLzRO2ZBwTtepnwHXW5VTrVU9eFGijMUqllg==",
+ "dependencies": {
+ "@octokit/auth-oauth-app": "^5.0.0",
+ "@octokit/auth-oauth-user": "^2.0.0",
+ "@octokit/request": "^6.0.0",
+ "@octokit/request-error": "^3.0.0",
+ "@octokit/types": "^9.0.0",
+ "deprecation": "^2.3.1",
+ "lru-cache": "^9.0.0",
+ "universal-github-app-jwt": "^1.1.1",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/auth-app/node_modules/lru-cache": {
+ "version": "9.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-9.1.1.tgz",
+ "integrity": "sha512-65/Jky17UwSb0BuB9V+MyDpsOtXKmYwzhyl+cOa9XUiI4uV2Ouy/2voFP3+al0BjZbJgMBD8FojMpAf+Z+qn4A==",
+ "engines": {
+ "node": "14 || >=16.14"
+ }
+ },
+ "node_modules/@octokit/auth-oauth-app": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmjs.org/@octokit/auth-oauth-app/-/auth-oauth-app-5.0.5.tgz",
+ "integrity": "sha512-UPX1su6XpseaeLVCi78s9droxpGtBWIgz9XhXAx9VXabksoF0MyI5vaa1zo1njyYt6VaAjFisC2A2Wchcu2WmQ==",
+ "dependencies": {
+ "@octokit/auth-oauth-device": "^4.0.0",
+ "@octokit/auth-oauth-user": "^2.0.0",
+ "@octokit/request": "^6.0.0",
+ "@octokit/types": "^9.0.0",
+ "@types/btoa-lite": "^1.0.0",
+ "btoa-lite": "^1.0.0",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/auth-oauth-device": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/@octokit/auth-oauth-device/-/auth-oauth-device-4.0.4.tgz",
+ "integrity": "sha512-Xl85BZYfqCMv+Uvz33nVVUjE7I/PVySNaK6dRRqlkvYcArSr9vRcZC9KVjXYObGRTCN6mISeYdakAZvWEN4+Jw==",
+ "dependencies": {
+ "@octokit/oauth-methods": "^2.0.0",
+ "@octokit/request": "^6.0.0",
+ "@octokit/types": "^9.0.0",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/auth-oauth-user": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/@octokit/auth-oauth-user/-/auth-oauth-user-2.1.1.tgz",
+ "integrity": "sha512-JgqnNNPf9CaWLxWm9uh2WgxcaVYhxBR09NVIPTiMU2dVZ3FObOHs3njBiLNw+zq84k+rEdm5Y7AsiASrZ84Apg==",
+ "dependencies": {
+ "@octokit/auth-oauth-device": "^4.0.0",
+ "@octokit/oauth-methods": "^2.0.0",
+ "@octokit/request": "^6.0.0",
+ "@octokit/types": "^9.0.0",
+ "btoa-lite": "^1.0.0",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/auth-token": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-3.0.3.tgz",
+ "integrity": "sha512-/aFM2M4HVDBT/jjDBa84sJniv1t9Gm/rLkalaz9htOm+L+8JMj1k9w0CkUdcxNyNxZPlTxKPVko+m1VlM58ZVA==",
+ "dependencies": {
+ "@octokit/types": "^9.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/core": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/@octokit/core/-/core-4.2.1.tgz",
+ "integrity": "sha512-tEDxFx8E38zF3gT7sSMDrT1tGumDgsw5yPG6BBh/X+5ClIQfMH/Yqocxz1PnHx6CHyF6pxmovUTOfZAUvQ0Lvw==",
+ "dependencies": {
+ "@octokit/auth-token": "^3.0.0",
+ "@octokit/graphql": "^5.0.0",
+ "@octokit/request": "^6.0.0",
+ "@octokit/request-error": "^3.0.0",
+ "@octokit/types": "^9.0.0",
+ "before-after-hook": "^2.2.0",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/endpoint": {
+ "version": "7.0.5",
+ "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.5.tgz",
+ "integrity": "sha512-LG4o4HMY1Xoaec87IqQ41TQ+glvIeTKqfjkCEmt5AIwDZJwQeVZFIEYXrYY6yLwK+pAScb9Gj4q+Nz2qSw1roA==",
+ "dependencies": {
+ "@octokit/types": "^9.0.0",
+ "is-plain-object": "^5.0.0",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/endpoint/node_modules/is-plain-object": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
+ "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/@octokit/graphql": {
+ "version": "5.0.6",
+ "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-5.0.6.tgz",
+ "integrity": "sha512-Fxyxdy/JH0MnIB5h+UQ3yCoh1FG4kWXfFKkpWqjZHw/p+Kc8Y44Hu/kCgNBT6nU1shNumEchmW/sUO1JuQnPcw==",
+ "dependencies": {
+ "@octokit/request": "^6.0.0",
+ "@octokit/types": "^9.0.0",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/oauth-authorization-url": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/oauth-authorization-url/-/oauth-authorization-url-5.0.0.tgz",
+ "integrity": "sha512-y1WhN+ERDZTh0qZ4SR+zotgsQUE1ysKnvBt1hvDRB2WRzYtVKQjn97HEPzoehh66Fj9LwNdlZh+p6TJatT0zzg==",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/oauth-methods": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@octokit/oauth-methods/-/oauth-methods-2.0.5.tgz",
+ "integrity": "sha512-yQP6B5gE3axNxuM3U9KqWs/ErAQ+WLPaPgC/7EjsZsQibkf8sjdAfF8/y/EJW+Dd05XQvadX4WhQZPMnO1SE1A==",
+ "dependencies": {
+ "@octokit/oauth-authorization-url": "^5.0.0",
+ "@octokit/request": "^6.2.3",
+ "@octokit/request-error": "^3.0.3",
+ "@octokit/types": "^9.0.0",
+ "btoa-lite": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/openapi-types": {
+ "version": "17.2.0",
+ "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-17.2.0.tgz",
+ "integrity": "sha512-MazrFNx4plbLsGl+LFesMo96eIXkFgEtaKbnNpdh4aQ0VM10aoylFsTYP1AEjkeoRNZiiPe3T6Gl2Hr8dJWdlQ=="
+ },
+ "node_modules/@octokit/plugin-paginate-rest": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-6.1.2.tgz",
+ "integrity": "sha512-qhrmtQeHU/IivxucOV1bbI/xZyC/iOBhclokv7Sut5vnejAIAEXVcGQeRpQlU39E0WwK9lNvJHphHri/DB6lbQ==",
+ "dependencies": {
+ "@octokit/tsconfig": "^1.0.2",
+ "@octokit/types": "^9.2.3"
+ },
+ "engines": {
+ "node": ">= 14"
+ },
+ "peerDependencies": {
+ "@octokit/core": ">=4"
+ }
+ },
+ "node_modules/@octokit/plugin-request-log": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz",
+ "integrity": "sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA==",
+ "peerDependencies": {
+ "@octokit/core": ">=3"
+ }
+ },
+ "node_modules/@octokit/plugin-rest-endpoint-methods": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-7.1.2.tgz",
+ "integrity": "sha512-R0oJ7j6f/AdqPLtB9qRXLO+wjI9pctUn8Ka8UGfGaFCcCv3Otx14CshQ89K4E88pmyYZS8p0rNTiprML/81jig==",
+ "dependencies": {
+ "@octokit/types": "^9.2.3",
+ "deprecation": "^2.3.1"
+ },
+ "engines": {
+ "node": ">= 14"
+ },
+ "peerDependencies": {
+ "@octokit/core": ">=3"
+ }
+ },
+ "node_modules/@octokit/request": {
+ "version": "6.2.5",
+ "resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.5.tgz",
+ "integrity": "sha512-z83E8UIlPNaJUsXpjD8E0V5o/5f+vJJNbNcBwVZsX3/vC650U41cOkTLjq4PKk9BYonQGOnx7N17gvLyNjgGcQ==",
+ "dependencies": {
+ "@octokit/endpoint": "^7.0.0",
+ "@octokit/request-error": "^3.0.0",
+ "@octokit/types": "^9.0.0",
+ "is-plain-object": "^5.0.0",
+ "node-fetch": "^2.6.7",
+ "universal-user-agent": "^6.0.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/request-error": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.3.tgz",
+ "integrity": "sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==",
+ "dependencies": {
+ "@octokit/types": "^9.0.0",
+ "deprecation": "^2.0.0",
+ "once": "^1.4.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/request/node_modules/is-plain-object": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz",
+ "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/@octokit/rest": {
+ "version": "19.0.11",
+ "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-19.0.11.tgz",
+ "integrity": "sha512-m2a9VhaP5/tUw8FwfnW2ICXlXpLPIqxtg3XcAiGMLj/Xhw3RSBfZ8le/466ktO1Gcjr8oXudGnHhxV1TXJgFxw==",
+ "dependencies": {
+ "@octokit/core": "^4.2.1",
+ "@octokit/plugin-paginate-rest": "^6.1.2",
+ "@octokit/plugin-request-log": "^1.0.4",
+ "@octokit/plugin-rest-endpoint-methods": "^7.1.2"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/tsconfig": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@octokit/tsconfig/-/tsconfig-1.0.2.tgz",
+ "integrity": "sha512-I0vDR0rdtP8p2lGMzvsJzbhdOWy405HcGovrspJ8RRibHnyRgggUSNO5AIox5LmqiwmatHKYsvj6VGFHkqS7lA=="
+ },
+ "node_modules/@octokit/types": {
+ "version": "9.2.3",
+ "resolved": "https://registry.npmjs.org/@octokit/types/-/types-9.2.3.tgz",
+ "integrity": "sha512-MMeLdHyFIALioycq+LFcA71v0S2xpQUX2cw6pPbHQjaibcHYwLnmK/kMZaWuGfGfjBJZ3wRUq+dOaWsvrPJVvA==",
+ "dependencies": {
+ "@octokit/openapi-types": "^17.2.0"
+ }
+ },
+ "node_modules/@octokit/webhooks": {
+ "version": "11.0.0",
+ "resolved": "https://registry.npmjs.org/@octokit/webhooks/-/webhooks-11.0.0.tgz",
+ "integrity": "sha512-+cn1O4+ItqXwc9Yo0DVfcfxPgeIRjV2AGDOkG6fwNRwXHw2IIUE/HEaNaHLUTiVCvXbL/pv6swqd+bM/Eylu5Q==",
+ "dependencies": {
+ "@octokit/request-error": "^3.0.0",
+ "@octokit/webhooks-methods": "^3.0.0",
+ "@octokit/webhooks-types": "6.11.0",
+ "aggregate-error": "^3.1.0"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/webhooks-methods": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@octokit/webhooks-methods/-/webhooks-methods-3.0.2.tgz",
+ "integrity": "sha512-Vlnv5WBscf07tyAvfDbp7pTkMZUwk7z7VwEF32x6HqI+55QRwBTcT+D7DDjZXtad/1dU9E32x0HmtDlF9VIRaQ==",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/@octokit/webhooks-types": {
+ "version": "6.11.0",
+ "resolved": "https://registry.npmjs.org/@octokit/webhooks-types/-/webhooks-types-6.11.0.tgz",
+ "integrity": "sha512-AanzbulOHljrku1NGfafxdpTCfw2ENaWzH01N2vqQM+cUFbk868Cgh0xylz0JIM9BoKbfI++bdD6EYX0Q/UTEw=="
+ },
"node_modules/@pkgr/utils": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@pkgr/utils/-/utils-2.3.1.tgz",
@@ -1064,6 +1360,11 @@
"node": ">=10.13.0"
}
},
+ "node_modules/@types/btoa-lite": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/@types/btoa-lite/-/btoa-lite-1.0.0.tgz",
+ "integrity": "sha512-wJsiX1tosQ+J5+bY5LrSahHxr2wT+uME5UDwdN1kg4frt40euqA+wzECkmq4t5QbveHiJepfdThgQrPw6KiSlg=="
+ },
"node_modules/@types/debug": {
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz",
@@ -1094,6 +1395,14 @@
"integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",
"dev": true
},
+ "node_modules/@types/jsonwebtoken": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",
+ "integrity": "sha512-drE6uz7QBKq1fYqqoFKTDRdFCPHd5TCub75BM+D+cMx7NU9hUz7SESLfC2fSCXVFMO5Yj8sOWHuGqPgjc+fz0Q==",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/mdast": {
"version": "3.0.10",
"resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.10.tgz",
@@ -1294,6 +1603,18 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
+ "node_modules/aggregate-error": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz",
+ "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==",
+ "dependencies": {
+ "clean-stack": "^2.0.0",
+ "indent-string": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/ajv": {
"version": "6.12.6",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
@@ -1562,6 +1883,11 @@
}
]
},
+ "node_modules/before-after-hook": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz",
+ "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ=="
+ },
"node_modules/bin-links": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/bin-links/-/bin-links-4.0.1.tgz",
@@ -1651,6 +1977,11 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/btoa-lite": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/btoa-lite/-/btoa-lite-1.0.0.tgz",
+ "integrity": "sha512-gvW7InbIyF8AicrqWoptdW08pUxuhq8BEgowNajy9RhiE86fmGAGl+bLKo6oB8QP0CkqHLowfN0oJdKC/J6LbA=="
+ },
"node_modules/buffer": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
@@ -1674,6 +2005,11 @@
"ieee754": "^1.1.13"
}
},
+ "node_modules/buffer-equal-constant-time": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="
+ },
"node_modules/bufferutil": {
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.7.tgz",
@@ -1852,6 +2188,14 @@
"node": ">=10"
}
},
+ "node_modules/clean-stack": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz",
+ "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/client-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
@@ -2378,6 +2722,11 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/deprecation": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz",
+ "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ=="
+ },
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
@@ -2505,6 +2854,14 @@
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
+ "node_modules/ecdsa-sig-formatter": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
"node_modules/electron-to-chromium": {
"version": "1.4.320",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.320.tgz",
@@ -3915,6 +4272,14 @@
"node": ">=0.8.19"
}
},
+ "node_modules/indent-string": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
+ "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -4463,6 +4828,21 @@
"node": ">=12.0.0"
}
},
+ "node_modules/jsonwebtoken": {
+ "version": "9.0.0",
+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.0.tgz",
+ "integrity": "sha512-tuGfYXxkQGDPnLJ7SibiQgVgeDgfbPq2k2ICcbgqW8WxWLBAxKQM/ZCu/IT8SOSwmaYl4dpTFCW5xZv7YbbWUw==",
+ "dependencies": {
+ "jws": "^3.2.2",
+ "lodash": "^4.17.21",
+ "ms": "^2.1.1",
+ "semver": "^7.3.8"
+ },
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ }
+ },
"node_modules/jsx-ast-utils": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.3.tgz",
@@ -4476,6 +4856,25 @@
"node": ">=4.0"
}
},
+ "node_modules/jwa": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",
+ "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",
+ "dependencies": {
+ "buffer-equal-constant-time": "1.0.1",
+ "ecdsa-sig-formatter": "1.0.11",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/jws": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",
+ "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",
+ "dependencies": {
+ "jwa": "^1.4.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
"node_modules/kleur": {
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
@@ -8084,6 +8483,20 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/universal-github-app-jwt": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/universal-github-app-jwt/-/universal-github-app-jwt-1.1.1.tgz",
+ "integrity": "sha512-G33RTLrIBMFmlDV4u4CBF7dh71eWwykck4XgaxaIVeZKOYZRAAxvcGMRFTUclVY6xoUPQvO4Ne5wKGxYm/Yy9w==",
+ "dependencies": {
+ "@types/jsonwebtoken": "^9.0.0",
+ "jsonwebtoken": "^9.0.0"
+ }
+ },
+ "node_modules/universal-user-agent": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz",
+ "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w=="
+ },
"node_modules/update-browserslist-db": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz",
diff --git a/package.json b/package.json
index adf4b743d..1d4a28b6d 100644
--- a/package.json
+++ b/package.json
@@ -40,6 +40,9 @@
},
"dependencies": {
"@devbookhq/splitter": "^1.4.0",
+ "@octokit/auth-app": "^4.0.13",
+ "@octokit/rest": "^19.0.11",
+ "@octokit/webhooks": "^11.0.0",
"@prisma/client": "^4.13.0",
"@supabase/auth-helpers-nextjs": "^0.5.5",
"@supabase/auth-helpers-react": "^0.3.1",
@@ -104,4 +107,4 @@
"tailwindcss": "^3.2.7",
"typescript": "^4.9.5"
}
-}
\ No newline at end of file
+}
diff --git a/pages/api/github/oauth.ts b/pages/api/github/oauth.ts
new file mode 100644
index 000000000..a6cf56908
--- /dev/null
+++ b/pages/api/github/oauth.ts
@@ -0,0 +1,45 @@
+// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
+import type { NextApiRequest, NextApiResponse } from 'next'
+import url from 'url'
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (!req.url) {
+ res.writeHead(400, { 'Content-Type': 'text/html' })
+ res.end('No request URL')
+ return
+ }
+
+ const { code }: { code?: string } = url.parse(req.url, true).query
+ if (!code) {
+ res.writeHead(400, { 'Content-Type': 'text/html' })
+ res.end('No code param in query')
+ return
+ }
+
+ const exchangeURL = new URL('login/oauth/access_token', 'https://github.com')
+ exchangeURL.searchParams.set('client_id', process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID!)
+ exchangeURL.searchParams.set('client_secret', process.env.GITHUB_CLIENT_SECRET!)
+ exchangeURL.searchParams.set('code', code)
+
+ const response = await fetch(exchangeURL.toString(), {
+ method: 'GET',
+ headers: {
+ Accept: 'application/json',
+ }
+ })
+ const {
+ access_token,
+ }: {
+ access_token: string,
+ } = await response.json()
+
+ const redirectionURL = new URL('github/callback', `https://${req.headers.host}`)
+
+ redirectionURL.searchParams.set('access_token', access_token)
+
+ res.writeHead(302, { 'Location': redirectionURL.toString() })
+ res.end()
+}
diff --git a/pages/api/github/webhook.ts b/pages/api/github/webhook.ts
new file mode 100644
index 000000000..d6b02afbd
--- /dev/null
+++ b/pages/api/github/webhook.ts
@@ -0,0 +1,9 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { getGitHubWebhooksMiddleware } from 'github/webhooks'
+
+const webhookHandler = getGitHubWebhooksMiddleware()
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ await (await webhookHandler)(req, res)
+}
diff --git a/pages/github/callback.ts b/pages/github/callback.ts
new file mode 100644
index 000000000..cc987c167
--- /dev/null
+++ b/pages/github/callback.ts
@@ -0,0 +1,25 @@
+import { useRouter } from 'next/router'
+import { useEffect } from 'react'
+
+function GitHubCallback() {
+ const router = useRouter()
+
+ useEffect(function message() {
+ if (router.query.access_token) {
+ if (window && window.opener) {
+ window.opener.postMessage({ accessToken: router.query.access_token }, '*')
+ window.close()
+ }
+ }
+ if (router.query.installation_id) {
+ if (window && window.opener) {
+ window.opener.postMessage({ installationID: router.query.installation_id }, '*')
+ window.close()
+ }
+ }
+ }, [router.query.access_token, router.query.installation_id])
+
+ return null
+}
+
+export default GitHubCallback
diff --git a/pages/repo.tsx b/pages/repo.tsx
new file mode 100644
index 000000000..a9608f0a2
--- /dev/null
+++ b/pages/repo.tsx
@@ -0,0 +1,260 @@
+import {
+ useEffect,
+ useState,
+} from 'react'
+import useSWRMutation from 'swr/mutation'
+import humanId from 'human-id'
+import {
+ GitBranch,
+ LayoutGrid,
+ Folder,
+ GithubIcon,
+ ExternalLink,
+ ArrowRight,
+} from 'lucide-react'
+import { useRouter } from 'next/router'
+import clsx from 'clsx'
+import Link from 'next/link'
+import dynamic from 'next/dynamic'
+
+import { PostProjectBody } from 'pages/api/project'
+import { apps } from 'database'
+import Text from 'components/typography/Text'
+import Input from 'components/Input'
+import Select from 'components/Select'
+import { defaultRepoPath } from 'utils/constants'
+import Button from 'components/Button'
+import SpinnerIcon from 'components/icons/Spinner'
+const Repos = dynamic(() => import('components/Repos'), { ssr: false })
+
+async function handlePostProject(url: string, { arg }: { arg: PostProjectBody }) {
+ return await fetch(url, {
+ method: 'POST',
+ body: JSON.stringify(arg),
+
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ }).then(r => r.json())
+}
+
+const re = /[^a-zA-Z0-9\-]/
+
+export default function NewProject() {
+ const [isCreating, setIsCreating] = useState(false)
+ const [repoSetup, setRepoSetup] = useState<Pick<PostProjectBody, 'accessToken' | 'installationID' | 'repositoryID'> & { fullName: string, defaultBranch: string, branches?: string[], url: string }>()
+ const [projectSetup, setProjectSetup] = useState<Pick<PostProjectBody, 'path' | 'branch' | 'id'>>()
+ const {
+ trigger: createProject,
+ } = useSWRMutation<Pick<apps, 'id' | 'repository_path'>>('/api/project', handlePostProject)
+ const [err, setErr] = useState<string>()
+ const router = useRouter()
+
+ useEffect(function initProjectSetup() {
+ if (!repoSetup) return
+ setProjectSetup(s => ({
+ id: s?.id || humanId({
+ separator: '-',
+ capitalize: false,
+ }),
+ branch: repoSetup.defaultBranch,
+ path: s?.path || defaultRepoPath,
+ }))
+ }, [repoSetup])
+
+ async function handleCreateProject() {
+ if (!repoSetup || !projectSetup) return
+
+ setErr(undefined)
+ setIsCreating(true)
+
+ const id = projectSetup.id.trim()
+
+ if (re.test(id)) {
+ setErr('Project name must be a combination of letters, numbers and dashes')
+ setIsCreating(false)
+ return
+ }
+
+ if (id.length > 63) {
+ setErr('Project name is too long. It must have 63 or less characters')
+ setIsCreating(false)
+ return
+ }
+
+ try {
+ const project = await createProject({
+ ...projectSetup,
+ ...repoSetup,
+ id,
+ })
+
+ if (project && 'statusCode' in project) {
+ setErr(`Project with name "${id}" already exists`)
+ setIsCreating(false)
+ return
+ }
+
+ router.push({
+ pathname: '/projects/[id]',
+ query: {
+ id,
+ },
+ })
+ } catch (err) {
+ console.error(err)
+ setIsCreating(false)
+ }
+ }
+
+ return (
+ <div
+ className="
+ flex
+ flex-1
+ flex-col
+ space-x-0
+ space-y-8
+ overflow-hidden
+ p-8
+ lg:p-12
+ "
+ >
+ <div className="flex">
+ <div className="items-center flex space-x-2">
+ <LayoutGrid size="30px" strokeWidth="1.5" />
+ <Text
+ size={Text.size.S1}
+ text="Create New Project"
+ />
+ </div>
+ </div>
+
+ <div className="flex flex-1 justify-center overflow-hidden min-h-[200px]">
+ <div className="w-[450px] max-h-[600px] flex flex-col space-y-2 overflow-hidden">
+ <div className="flex space-x-2 items-center transition-all">
+ <Text
+ text="Select repository"
+ className={clsx('text-base', { 'text-slate-300 hover:text-green-800 cursor-pointer': repoSetup })}
+ onClick={() => setRepoSetup(undefined)}
+ />
+ <ArrowRight size="18px" className="text-slate-300" />
+ <Text
+ text="Configure project"
+ className={clsx(
+ 'text-base',
+ { 'text-slate-300': !repoSetup },
+ )}
+ />
+ </div>
+ <div
+ className={clsx(
+ 'flex overflow-hidden flex-1',
+ { 'hidden': repoSetup },
+ )}
+ >
+ <Repos
+ onRepoSelection={setRepoSetup}
+ />
+ </div>
+ {repoSetup &&
+ <div className="space-y-2 flex-1 flex flex-col">
+ <div
+ className="space-y-6 rounded border p-8 flex flex-col bg-white"
+ >
+ <div className="flex flex-col space-y-6">
+ <div className="flex flex-col flex-1 space-y-1">
+ <Input
+ title="Must be a combination of letters, numbers and dashes"
+ pattern="[^a-zA-Z0-9\-]"
+ label="Project name"
+ placeholder="Project name"
+ value={projectSetup?.id}
+ onChange={v => setProjectSetup(p => p ? ({ ...p, id: v }) : undefined)}
+ required
+ autofocus
+ />
+ <Text
+ text="Combination of letters, numbers and dashes"
+ size={Text.size.S3}
+ className="text-slate-400"
+ />
+ </div>
+
+ <div className="flex space-x-2 items-start">
+ <GithubIcon size="16px" />
+ <div className="flex flex-col space-y-1">
+ <Text text="Repository" size={Text.size.S3} />
+ <Link
+ href={{
+ pathname: repoSetup.url,
+ }}
+ className="flex space-x-1 hover:text-blue-600"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <Text
+ text={`${repoSetup?.fullName}`}
+ className="font-semibold underline"
+ />
+ <ExternalLink size="12px" />
+ </Link>
+ </div>
+ </div>
+
+ <div className="flex items-start space-x-2">
+ <GitBranch size="16px" />
+ <div className="flex flex-col space-y-1">
+ <Text text="Branch" size={Text.size.S3} />
+ <Select
+ items={(repoSetup?.branches || []).map(r => ({
+ label: r,
+ value: r,
+ })).sort((a, b) => {
+ return a.label.localeCompare(b.label)
+ })}
+ onSelect={(i) => {
+ setProjectSetup(s => s ? ({ ...s, branch: i?.value || s.branch }) : undefined)
+ }}
+ selectedItemLabel={projectSetup?.branch}
+ isTransparent
+ />
+ </div>
+ </div>
+
+ <div className="flex items-start space-x-2">
+ <Folder size="16px" />
+ <Input
+ label="Root directory"
+ placeholder="Root directory"
+ value={projectSetup?.path}
+ onChange={v => setProjectSetup(p => p ? ({ ...p, path: v }) : undefined)}
+ isTransparent
+ />
+ </div>
+ </div>
+ <div className="flex justify-center flex-col space-y-4">
+ <Button
+ isDisabled={!projectSetup || !repoSetup || !projectSetup.id || !projectSetup.branch || !projectSetup.path || isCreating || re.test(projectSetup.id.trim())}
+ onClick={handleCreateProject}
+ text={isCreating ? 'Creating & deploying' : 'Create project'}
+ variant={Button.variant.Full}
+ className="self-center whitespace-nowrap"
+ icon={isCreating ? <SpinnerIcon className="text-white" /> : null}
+ />
+ {!isCreating && err && (
+ <Text
+ className="self-center text-red-500"
+ size={Text.size.S3}
+ text={err}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ }
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/utils/popupModal.ts b/utils/popupModal.ts
new file mode 100644
index 000000000..9e87e69d1
--- /dev/null
+++ b/utils/popupModal.ts
@@ -0,0 +1,33 @@
+export function openPopupModal(url: URL) {
+ const features = {
+ popup: 'yes',
+ width: 820,
+ height: 700,
+ top: 'auto',
+ left: 'auto',
+ toolbar: 'no',
+ menubar: 'no',
+ }
+ const strWindowsFeatures = Object.entries(features)
+ .reduce((str, [key, value]) => {
+ if (value == 'auto') {
+ if (key === 'top') {
+ const v = Math.round(
+ window.innerHeight / 2 - features.height / 2
+ )
+ str += `top=${v},`
+ } else if (key === 'left') {
+ const v = Math.round(
+ window.innerWidth / 2 - features.width / 2
+ )
+ str += `left=${v},`
+ }
+ return str
+ }
+
+ str += `${key}=${value},`
+ return str
+ }, '')
+ .slice(0, -1) // remove last ',' (comma)
+ return window.open(url, '_blank', strWindowsFeatures)
+}