Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Add settings page with API key
Jakub Novak8e846e588a58
diff --git a/apps/dashboard/components/Layout.tsx b/apps/dashboard/components/Layout.tsxindex 56b6156d7..9c78d5f76 100644--- a/apps/dashboard/components/Layout.tsx+++ b/apps/dashboard/components/Layout.tsx@@ -11,7 +11,6 @@ import { usePostHog } from 'posthog-js/react'import { useSupabaseClient } from '@supabase/auth-helpers-react'import {Menu,- List,} from 'lucide-react'import Script from 'next/script'@@ -66,12 +65,12 @@ function Layout({ children }: PropsWithChildren) {const view = process.env.NEXT_PUBLIC_SHOW_UPLOADED_LOGS === '1'const showView = router.query['view'] === 'logs' ? 'logs' : view- const navigation = [- {- name: showView === 'logs' ? 'Agent Logs' : 'Agent Deployments',- icon: List,- },- ]+ const navigation = []+ // {+ // name: showView === 'logs' ? 'Agent Logs' : 'Agent Deployments',+ // icon: List,+ // },+ // ]return (<>diff --git a/apps/dashboard/components/Settings.tsx b/apps/dashboard/components/Settings.tsxnew file mode 100644index 000000000..27d0342a8--- /dev/null+++ b/apps/dashboard/components/Settings.tsx@@ -0,0 +1,24 @@+import APIKey from './Settings/APIKey.tsx'+++export interface Props {+ apiKey: string+}++function Settings({ apiKey }: Props) {+ return (+ <main className="overflow-hidden flex flex-col max-h-full flex-1 rounded-md">+ <header className="flex items-center px-4 py-3 border-b border-b-white/5 justify-between">+ <div className="flex items-center space-x-2">+ <h1 className="text-2xl font-semibold text-white">Settings</h1>+ </div>+ </header>+ <div className="space-x-4 overflow-hidden m-4">+ <div className="text-xl font-semibold text-white">API key</div>+ <APIKey apiKey={apiKey} />+ </div>+ </main>+ )+}++export default Settingsdiff --git a/apps/dashboard/components/Settings/APIKey.tsx b/apps/dashboard/components/Settings/APIKey.tsxnew file mode 100644index 000000000..863734390--- /dev/null+++ b/apps/dashboard/components/Settings/APIKey.tsx@@ -0,0 +1,25 @@+'use client'+import { CopyIcon } from 'lucide-react'++interface Props {+ apiKey: string;+}++function APIKey({ apiKey }: Props) {+ return (+ <div className="my-4 flex align-bottom justify-between w-3/4">+ <div+ className="mr-4 w-full text-center space-x-2 text-gray-200 border-2 rounded-md border-gray-200"+ >+ <span className="p-2 font-semibold">{apiKey}</span>+ </div>+ <CopyIcon+ onClick={() => navigator.clipboard.writeText(apiKey)}+ className="cursor-pointer place-self-center text-gray-200 hover:text-gray-400"+ size={24}+ />+ </div>+ )+}++export default APIKeydiff --git a/apps/dashboard/db/supabase.ts b/apps/dashboard/db/supabase.tsindex 2670b094c..c1b0c8bd6 100644--- a/apps/dashboard/db/supabase.ts+++ b/apps/dashboard/db/supabase.ts@@ -3,7 +3,7 @@ export type Json =| number| boolean| null- | { [key: string]: Json }+ | { [key: string]: Json | undefined }| Json[]export interface Database {@@ -21,6 +21,7 @@ export interface Database {logs_raw: string | nullproject_id: stringroute_id: string | null+ secrets: string | nullstate: Database["public"]["Enums"]["deployment_state"] | nullurl: string | null}@@ -35,6 +36,7 @@ export interface Database {logs_raw?: string | nullproject_id: stringroute_id?: string | null+ secrets?: string | nullstate?: Database["public"]["Enums"]["deployment_state"] | nullurl?: string | null}@@ -49,6 +51,7 @@ export interface Database {logs_raw?: string | nullproject_id?: stringroute_id?: string | null+ secrets?: string | nullstate?: Database["public"]["Enums"]["deployment_state"] | nullurl?: string | null}@@ -133,6 +136,12 @@ export interface Database {referencedRelation: "deployments"referencedColumns: ["id"]},+ {+ foreignKeyName: "log_files_deployment_id_fkey"+ columns: ["deployment_id"]+ referencedRelation: "decrypted_deployments"+ referencedColumns: ["id"]+ },{foreignKeyName: "log_files_log_upload_id_fkey"columns: ["log_upload_id"]@@ -218,6 +227,31 @@ export interface Database {}]}+ team_api_keys: {+ Row: {+ api_key: string+ created_at: string+ team_id: string+ }+ Insert: {+ api_key: string+ created_at?: string+ team_id: string+ }+ Update: {+ api_key?: string+ created_at?: string+ team_id?: string+ }+ Relationships: [+ {+ foreignKeyName: "team_api_keys_team_id_fkey"+ columns: ["team_id"]+ referencedRelation: "teams"+ referencedColumns: ["id"]+ }+ ]+ }teams: {Row: {created_at: string@@ -272,7 +306,64 @@ export interface Database {}}Views: {- [_ in never]: never+ decrypted_deployments: {+ Row: {+ auth: Json | null+ config: Json | null+ created_at: string | null+ decrypted_secrets: string | null+ enabled: boolean | null+ id: string | null+ last_finished_prompt: string | null+ logs: Json[] | null+ logs_raw: string | null+ project_id: string | null+ route_id: string | null+ secrets: string | null+ state: Database["public"]["Enums"]["deployment_state"] | null+ url: string | null+ }+ Insert: {+ auth?: Json | null+ config?: Json | null+ created_at?: string | null+ decrypted_secrets?: never+ enabled?: boolean | null+ id?: string | null+ last_finished_prompt?: string | null+ logs?: Json[] | null+ logs_raw?: string | null+ project_id?: string | null+ route_id?: string | null+ secrets?: string | null+ state?: Database["public"]["Enums"]["deployment_state"] | null+ url?: string | null+ }+ Update: {+ auth?: Json | null+ config?: Json | null+ created_at?: string | null+ decrypted_secrets?: never+ enabled?: boolean | null+ id?: string | null+ last_finished_prompt?: string | null+ logs?: Json[] | null+ logs_raw?: string | null+ project_id?: string | null+ route_id?: string | null+ secrets?: string | null+ state?: Database["public"]["Enums"]["deployment_state"] | null+ url?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "deployments_project_id_fkey"+ columns: ["project_id"]+ referencedRelation: "projects"+ referencedColumns: ["id"]+ }+ ]+ }}Functions: {append_array: {diff --git a/apps/dashboard/package-lock.json b/apps/dashboard/package-lock.jsonindex 1daa78524..78a6b90ea 100644--- a/apps/dashboard/package-lock.json+++ b/apps/dashboard/package-lock.json@@ -27,6 +27,7 @@"@tiptap/starter-kit": "^2.0.0-beta.220","@vercel/og": "^0.5.8","clsx": "^1.2.1",+ "crc32": "^0.2.2","cross-fetch": "^3.1.5","exponential-backoff": "^3.1.1","http-proxy-middleware": "^3.0.0-beta.1",@@ -2826,6 +2827,17 @@"url": "https://github.com/sponsors/mesqueeb"}},+ "node_modules/crc32": {+ "version": "0.2.2",+ "resolved": "https://registry.npmjs.org/crc32/-/crc32-0.2.2.tgz",+ "integrity": "sha512-PFZEGbDUeoNbL2GHIEpJRQGheXReDody/9axKTxhXtQqIL443wnNigtVZO9iuCIMPApKZRv7k2xr8euXHqNxQQ==",+ "bin": {+ "crc32": "bin/runner.js"+ },+ "engines": {+ "node": ">= 0.4.0"+ }+ },"node_modules/crelt": {"version": "1.0.5","resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.5.tgz",diff --git a/apps/dashboard/package.json b/apps/dashboard/package.jsonindex 6235e248d..48dd1e4bf 100644--- a/apps/dashboard/package.json+++ b/apps/dashboard/package.json@@ -59,6 +59,7 @@"@tiptap/starter-kit": "^2.0.0-beta.220","@vercel/og": "^0.5.8","clsx": "^1.2.1",+ "crc32": "^0.2.2","cross-fetch": "^3.1.5","exponential-backoff": "^3.1.1","http-proxy-middleware": "^3.0.0-beta.1",diff --git a/apps/dashboard/pages/index.tsx b/apps/dashboard/pages/index.tsxindex 8dc88f7bb..1c7af5f5b 100644--- a/apps/dashboard/pages/index.tsx+++ b/apps/dashboard/pages/index.tsx@@ -220,6 +220,13 @@ export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {},})+ return {+ redirect: {+ destination: '/settings',+ permanent: false,+ },+ }+return {props: {view: showUploadedLogs ? 'logs' : 'deployments',diff --git a/apps/dashboard/pages/settings/index.tsx b/apps/dashboard/pages/settings/index.tsxnew file mode 100644index 000000000..bc2066cad--- /dev/null+++ b/apps/dashboard/pages/settings/index.tsx@@ -0,0 +1,109 @@+import type { GetServerSideProps } from 'next'+import { createServerSupabaseClient } from '@supabase/auth-helpers-nextjs'++import { prisma } from 'db/prisma'+import { serverCreds } from 'db/credentials'+import Settings from 'components/Settings'+import { client as posthog } from '../../utils/posthog.ts'+import { generateApiKey } from '../../utils/apiKey.ts'++export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {+ const supabase = createServerSupabaseClient(ctx, serverCreds)+ const {+ data: { session },+ } = await supabase.auth.getSession()++ if (!session) {+ return {+ redirect: {+ destination: '/sign',+ permanent: false,+ },+ }+ }++ let apiKey = await prisma.team_api_keys.findFirst({+ include: {+ teams: {+ include: {+ users_teams: {+ where: {+ user_id: {+ equals: session.user.id,+ },+ },+ },+ },+ },+ },+ })++ if (!apiKey) {+ const user = await prisma.auth_users.findUnique({+ where: {+ id: session.user.id,+ },+ include: {+ users_teams: {+ include: {+ teams: true,+ },+ },+ },+ })+ if (!user) {+ return res.status(401).json({+ error: 'invalid_user',+ })+ }+ const defaultTeam = user.users_teams.find((t) => t.teams.is_default)+ if (!defaultTeam) {+ return {+ redirect: {+ destination: '/',+ permanent: false,+ },+ }+ }++ while (true) {+ const generatedApiKey = generateApiKey()+ try {+ apiKey = await prisma.team_api_keys.create({+ data: {+ team_id: defaultTeam.teams.id,+ api_key: generatedApiKey,+ },+ })+ break+ } catch (e) {+ // Duplicate key error+ if (e.code !== 'P2002') {+ throw e+ }+ }+ }++ posthog?.capture({+ distinctId: user.id,+ event: 'created API key',+ team: defaultTeam.teams.team_id,+ })+ }++ return {+ props: {+ apiKey: apiKey.api_key,+ },+ }+}++interface Props {+ apiKey: string;+}++function SettingsPage({ apiKey }: Props) {+ return <Settings apiKey={apiKey} />+}++export default SettingsPagediff --git a/prisma/schema.prisma b/apps/dashboard/prisma/schema.prismasimilarity index 95%rename from prisma/schema.prismarename to apps/dashboard/prisma/schema.prismaindex 6f0446410..0258b481a 100644--- a/prisma/schema.prisma+++ b/apps/dashboard/prisma/schema.prisma@@ -235,12 +235,13 @@ model auth_users {}model teams {- id String @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid- created_at DateTime @default(now()) @db.Timestamptz(6)- is_default Boolean?- name String @default("")- projects projects[]- users_teams users_teams[]+ id String @id @default(dbgenerated("uuid_generate_v4()")) @db.Uuid+ created_at DateTime @default(now()) @db.Timestamptz(6)+ is_default Boolean?+ name String @default("")+ projects projects[]+ team_api_keys team_api_keys[]+ users_teams users_teams[]@@schema("public")}@@ -355,6 +356,16 @@ model log_uploads {@@schema("public")}+/// This model contains row level security and requires additional setup for migrations. Visit https://pris.ly/d/row-level-security for more info.+model team_api_keys {+ api_key String @id @db.VarChar(42)+ created_at DateTime @default(now()) @db.Timestamptz(6)+ team_id String @db.Uuid+ teams teams @relation(fields: [team_id], references: [id], onDelete: NoAction, onUpdate: NoAction)++ @@schema("public")+}+/// The underlying view does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.view decrypted_deployments {id String? @db.Uuiddiff --git a/prisma/views/public/decrypted_deployments.sql b/apps/dashboard/prisma/views/public/decrypted_deployments.sqlsimilarity index 100%rename from prisma/views/public/decrypted_deployments.sqlrename to apps/dashboard/prisma/views/public/decrypted_deployments.sqldiff --git a/apps/dashboard/utils/apiKey.ts b/apps/dashboard/utils/apiKey.tsnew file mode 100644index 000000000..46d445a6b--- /dev/null+++ b/apps/dashboard/utils/apiKey.ts@@ -0,0 +1,39 @@+import crypto from 'crypto'+import crc32 from 'crc32'++const base62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'++function numberToBase62(number, length) {+ const base = base62.length++ let result = ''+ while (number > 0) {+ result = base62[number % base] + result+ number = Math.floor(number / base)+ }++ while (result.length < length) {+ result = '0' + result+ }++ return result+}+function generateBase62String(length) {+ const base = base62.length++ const randomBytes = crypto.randomBytes(length)+ let result = ''++ for (let i = 0; i < length; i++) {+ const byteValue = randomBytes.readUInt8(i)+ result += base62[byteValue % base]+ }++ return result+}+export function generateApiKey() {+ const randomString = generateBase62String(32)+ const checksum = crc32(randomString)+ const checksumEncoded = numberToBase62(parseInt(checksum, 16), 6)+ return 'pk_' + randomString + '_' + checksumEncoded+}