1- import { createDecipheriv , createHash } from 'crypto'
2- import { and , eq } from 'drizzle-orm'
31import { type NextRequest , NextResponse } from 'next/server'
42import { getSession } from '@/lib/auth'
53import { env } from '@/lib/env'
64import { createLogger } from '@/lib/logs/console/logger'
7- import { db } from '@/db'
8- import { copilotApiKeys } from '@/db/schema'
5+ import { SIM_AGENT_API_URL_DEFAULT } from '@/lib/sim-agent'
96
107const logger = createLogger ( 'CopilotApiKeys' )
118
12- function deriveKey ( keyString : string ) : Buffer {
13- return createHash ( 'sha256' ) . update ( keyString , 'utf8' ) . digest ( )
14- }
15-
16- function decryptWithKey ( encryptedValue : string , keyString : string ) : string {
17- const parts = encryptedValue . split ( ':' )
18- if ( parts . length !== 3 ) {
19- throw new Error ( 'Invalid encrypted value format' )
20- }
21- const [ ivHex , encryptedHex , authTagHex ] = parts
22- const key = deriveKey ( keyString )
23- const iv = Buffer . from ( ivHex , 'hex' )
24- const decipher = createDecipheriv ( 'aes-256-gcm' , key , iv )
25- decipher . setAuthTag ( Buffer . from ( authTagHex , 'hex' ) )
26- let decrypted = decipher . update ( encryptedHex , 'hex' , 'utf8' )
27- decrypted += decipher . final ( 'utf8' )
28- return decrypted
29- }
9+ const SIM_AGENT_API_URL = env . SIM_AGENT_API_URL || SIM_AGENT_API_URL_DEFAULT
3010
3111export async function GET ( request : NextRequest ) {
3212 try {
@@ -35,22 +15,28 @@ export async function GET(request: NextRequest) {
3515 return NextResponse . json ( { error : 'Unauthorized' } , { status : 401 } )
3616 }
3717
38- if ( ! env . AGENT_API_DB_ENCRYPTION_KEY ) {
39- logger . error ( 'AGENT_API_DB_ENCRYPTION_KEY is not set' )
40- return NextResponse . json ( { error : 'Server not configured' } , { status : 500 } )
18+ const userId = session . user . id
19+
20+ const res = await fetch ( `${ SIM_AGENT_API_URL } /api/validate-key/get-api-keys` , {
21+ method : 'POST' ,
22+ headers : { 'Content-Type' : 'application/json' } ,
23+ body : JSON . stringify ( { userId } ) ,
24+ } )
25+
26+ if ( ! res . ok ) {
27+ const errorBody = await res . text ( ) . catch ( ( ) => '' )
28+ logger . error ( 'Sim Agent get-api-keys error' , { status : res . status , error : errorBody } )
29+ return NextResponse . json ( { error : 'Failed to get keys' } , { status : res . status || 500 } )
4130 }
4231
43- const userId = session . user . id
32+ const apiKeys = ( await res . json ( ) . catch ( ( ) => null ) ) as { id : string ; apiKey : string } [ ] | null
4433
45- const rows = await db
46- . select ( { id : copilotApiKeys . id , apiKeyEncrypted : copilotApiKeys . apiKeyEncrypted } )
47- . from ( copilotApiKeys )
48- . where ( eq ( copilotApiKeys . userId , userId ) )
34+ if ( ! Array . isArray ( apiKeys ) ) {
35+ logger . error ( 'Sim Agent get-api-keys returned invalid payload' )
36+ return NextResponse . json ( { error : 'Invalid response from Sim Agent' } , { status : 500 } )
37+ }
4938
50- const keys = rows . map ( ( row ) => ( {
51- id : row . id ,
52- apiKey : decryptWithKey ( row . apiKeyEncrypted , env . AGENT_API_DB_ENCRYPTION_KEY as string ) ,
53- } ) )
39+ const keys = apiKeys
5440
5541 return NextResponse . json ( { keys } , { status : 200 } )
5642 } catch ( error ) {
@@ -73,9 +59,23 @@ export async function DELETE(request: NextRequest) {
7359 return NextResponse . json ( { error : 'id is required' } , { status : 400 } )
7460 }
7561
76- await db
77- . delete ( copilotApiKeys )
78- . where ( and ( eq ( copilotApiKeys . userId , userId ) , eq ( copilotApiKeys . id , id ) ) )
62+ const res = await fetch ( `${ SIM_AGENT_API_URL } /api/validate-key/delete` , {
63+ method : 'POST' ,
64+ headers : { 'Content-Type' : 'application/json' } ,
65+ body : JSON . stringify ( { userId, apiKeyId : id } ) ,
66+ } )
67+
68+ if ( ! res . ok ) {
69+ const errorBody = await res . text ( ) . catch ( ( ) => '' )
70+ logger . error ( 'Sim Agent delete key error' , { status : res . status , error : errorBody } )
71+ return NextResponse . json ( { error : 'Failed to delete key' } , { status : res . status || 500 } )
72+ }
73+
74+ const data = ( await res . json ( ) . catch ( ( ) => null ) ) as { success ?: boolean } | null
75+ if ( ! data ?. success ) {
76+ logger . error ( 'Sim Agent delete key returned invalid payload' )
77+ return NextResponse . json ( { error : 'Invalid response from Sim Agent' } , { status : 500 } )
78+ }
7979
8080 return NextResponse . json ( { success : true } , { status : 200 } )
8181 } catch ( error ) {
0 commit comments