chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
@@ -0,0 +1,58 @@
import { type NextRequest, NextResponse } from 'next/server'
import { generateCopilotApiKeyContract } from '@/lib/api/contracts'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { TraceAttr } from '@/lib/copilot/generated/trace-attributes-v1'
import { fetchGo } from '@/lib/copilot/request/go/fetch'
import { getMothershipBaseURL } from '@/lib/copilot/server/agent-url'
import { env } from '@/lib/core/config/env'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
export const POST = withRouteHandler(async (req: NextRequest) => {
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = session.user.id
const mothershipBaseURL = await getMothershipBaseURL({ userId })
const parsed = await parseRequest(generateCopilotApiKeyContract, req, {})
if (!parsed.success) return parsed.response
const { name } = parsed.data.body
const res = await fetchGo(`${mothershipBaseURL}/api/validate-key/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(env.COPILOT_API_KEY ? { 'x-api-key': env.COPILOT_API_KEY } : {}),
},
body: JSON.stringify({ userId, name }),
spanName: 'sim → go /api/validate-key/generate',
operation: 'generate_api_key',
attributes: { [TraceAttr.UserId]: userId },
})
if (!res.ok) {
return NextResponse.json(
{ error: 'Failed to generate copilot API key' },
{ status: res.status || 500 }
)
}
const data = (await res.json().catch(() => null)) as { apiKey?: string; id?: string } | null
if (!data?.apiKey) {
return NextResponse.json({ error: 'Invalid response from Sim Agent' }, { status: 500 })
}
return NextResponse.json(
{ success: true, key: { id: data?.id || 'new', apiKey: data.apiKey } },
{ status: 201 }
)
} catch (error) {
return NextResponse.json({ error: 'Failed to generate copilot API key' }, { status: 500 })
}
})
@@ -0,0 +1,395 @@
/**
* Tests for copilot api-keys API route
*
* @vitest-environment node
*/
import { authMockFns, createEnvMock } from '@sim/testing'
import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { mockFetch, mockGetMothershipBaseURL } = vi.hoisted(() => ({
mockFetch: vi.fn(),
mockGetMothershipBaseURL: vi.fn(),
}))
vi.mock('@/lib/copilot/constants', () => ({
SIM_AGENT_API_URL_DEFAULT: 'https://agent.sim.example.com',
SIM_AGENT_API_URL: 'https://agent.sim.example.com',
COPILOT_MODES: ['ask', 'build', 'plan'] as const,
COPILOT_REQUEST_MODES: ['ask', 'build', 'plan', 'agent'] as const,
}))
vi.mock('@/lib/copilot/server/agent-url', () => ({
getMothershipBaseURL: mockGetMothershipBaseURL,
}))
vi.mock('@/lib/core/config/env', () => createEnvMock({ COPILOT_API_KEY: 'test-api-key' }))
import { DELETE, GET } from '@/app/api/copilot/api-keys/route'
// `fetchGo` reads `response.status` and `response.headers.get('content-length')`
// to stamp span attributes, so mock responses need both fields or the call
// path throws before the route handler sees the body.
function buildMockResponse(init: {
ok: boolean
status?: number
json: () => Promise<unknown>
}): Record<string, unknown> {
return {
ok: init.ok,
status: init.status ?? (init.ok ? 200 : 500),
headers: new Headers(),
json: init.json,
}
}
describe('Copilot API Keys API Route', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetMothershipBaseURL.mockResolvedValue('https://agent.sim.example.com')
global.fetch = mockFetch
})
describe('GET', () => {
it('should return 401 when user is not authenticated', async () => {
authMockFns.mockGetSession.mockResolvedValue(null)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(401)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Unauthorized' })
})
it('should return list of API keys with masked values', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
const mockApiKeys = [
{
id: 'key-1',
apiKey: 'sk-sim-abcdefghijklmnopqrstuv',
name: 'Production Key',
createdAt: '2024-01-01T00:00:00.000Z',
lastUsed: '2024-01-15T00:00:00.000Z',
},
{
id: 'key-2',
apiKey: 'sk-sim-zyxwvutsrqponmlkjihgfe',
name: null,
createdAt: '2024-01-02T00:00:00.000Z',
lastUsed: null,
},
]
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.resolve(mockApiKeys),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(200)
const responseData = await response.json()
expect(responseData.keys).toHaveLength(2)
expect(responseData.keys[0].id).toBe('key-1')
expect(responseData.keys[0].displayKey).toBe('•••••qrstuv')
expect(responseData.keys[0].name).toBe('Production Key')
expect(responseData.keys[1].displayKey).toBe('•••••jihgfe')
expect(responseData.keys[1].name).toBeNull()
})
it('should return empty array when user has no API keys', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.resolve([]),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(200)
const responseData = await response.json()
expect(responseData.keys).toEqual([])
})
it('should forward userId to Sim Agent', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.resolve([]),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
await GET(request)
expect(mockFetch).toHaveBeenCalledWith(
'https://agent.sim.example.com/api/validate-key/get-api-keys',
expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({
'Content-Type': 'application/json',
'x-api-key': 'test-api-key',
}),
body: JSON.stringify({ userId: 'user-123' }),
})
)
})
it('should return error when Sim Agent returns non-ok response', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: false,
status: 503,
json: () => Promise.resolve({ error: 'Service unavailable' }),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(503)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Failed to get keys' })
})
it('should return 500 when Sim Agent returns invalid response', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.resolve({ invalid: 'response' }),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(500)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Invalid response from Sim Agent' })
})
it('should handle network errors gracefully', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockRejectedValueOnce(new Error('Network error'))
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(500)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Failed to get keys' })
})
it('should handle API keys with empty apiKey string', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
const mockApiKeys = [
{
id: 'key-1',
apiKey: '',
name: 'Empty Key',
createdAt: '2024-01-01T00:00:00.000Z',
lastUsed: null,
},
]
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.resolve(mockApiKeys),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(200)
const responseData = await response.json()
expect(responseData.keys[0].displayKey).toBe('•••••')
})
it('should handle JSON parsing errors from Sim Agent', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.reject(new Error('Invalid JSON')),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await GET(request)
expect(response.status).toBe(500)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Invalid response from Sim Agent' })
})
})
describe('DELETE', () => {
it('should return 401 when user is not authenticated', async () => {
authMockFns.mockGetSession.mockResolvedValue(null)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys?id=key-123')
const response = await DELETE(request)
expect(response.status).toBe(401)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Unauthorized' })
})
it('should return 400 when id parameter is missing', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys')
const response = await DELETE(request)
expect(response.status).toBe(400)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'id is required' })
})
it('should successfully delete an API key', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.resolve({ success: true }),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys?id=key-123')
const response = await DELETE(request)
expect(response.status).toBe(200)
const responseData = await response.json()
expect(responseData).toEqual({ success: true })
expect(mockFetch).toHaveBeenCalledWith(
'https://agent.sim.example.com/api/validate-key/delete',
expect.objectContaining({
method: 'POST',
headers: expect.objectContaining({
'Content-Type': 'application/json',
'x-api-key': 'test-api-key',
}),
body: JSON.stringify({ userId: 'user-123', apiKeyId: 'key-123' }),
})
)
})
it('should return error when Sim Agent returns non-ok response', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: false,
status: 404,
json: () => Promise.resolve({ error: 'Key not found' }),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys?id=non-existent')
const response = await DELETE(request)
expect(response.status).toBe(404)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Failed to delete key' })
})
it('should return 500 when Sim Agent returns invalid response', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.resolve({ success: false }),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys?id=key-123')
const response = await DELETE(request)
expect(response.status).toBe(500)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Invalid response from Sim Agent' })
})
it('should handle network errors gracefully', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockRejectedValueOnce(new Error('Network error'))
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys?id=key-123')
const response = await DELETE(request)
expect(response.status).toBe(500)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Failed to delete key' })
})
it('should handle JSON parsing errors from Sim Agent on delete', async () => {
authMockFns.mockGetSession.mockResolvedValue({
user: { id: 'user-123', email: 'test@example.com' },
})
mockFetch.mockResolvedValueOnce(
buildMockResponse({
ok: true,
json: () => Promise.reject(new Error('Invalid JSON')),
})
)
const request = new NextRequest('http://localhost:3000/api/copilot/api-keys?id=key-123')
const response = await DELETE(request)
expect(response.status).toBe(500)
const responseData = await response.json()
expect(responseData).toEqual({ error: 'Invalid response from Sim Agent' })
})
})
})
+105
View File
@@ -0,0 +1,105 @@
import { type NextRequest, NextResponse } from 'next/server'
import { deleteCopilotApiKeyQuerySchema } from '@/lib/api/contracts'
import { getSession } from '@/lib/auth'
import { TraceAttr } from '@/lib/copilot/generated/trace-attributes-v1'
import { fetchGo } from '@/lib/copilot/request/go/fetch'
import { getMothershipBaseURL } from '@/lib/copilot/server/agent-url'
import { env } from '@/lib/core/config/env'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
export const GET = withRouteHandler(async (request: NextRequest) => {
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = session.user.id
const mothershipBaseURL = await getMothershipBaseURL({ userId })
const res = await fetchGo(`${mothershipBaseURL}/api/validate-key/get-api-keys`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(env.COPILOT_API_KEY ? { 'x-api-key': env.COPILOT_API_KEY } : {}),
},
body: JSON.stringify({ userId }),
spanName: 'sim → go /api/validate-key/get-api-keys',
operation: 'get_api_keys',
attributes: { [TraceAttr.UserId]: userId },
})
if (!res.ok) {
return NextResponse.json({ error: 'Failed to get keys' }, { status: res.status || 500 })
}
const apiKeys = (await res.json().catch(() => null)) as
| { id: string; apiKey: string; name?: string; createdAt?: string; lastUsed?: string }[]
| null
if (!Array.isArray(apiKeys)) {
return NextResponse.json({ error: 'Invalid response from Sim Agent' }, { status: 500 })
}
const keys = apiKeys.map((k) => {
const value = typeof k.apiKey === 'string' ? k.apiKey : ''
const last6 = value.slice(-6)
const displayKey = `•••••${last6}`
return {
id: k.id,
displayKey,
name: k.name || null,
createdAt: k.createdAt || null,
lastUsed: k.lastUsed || null,
}
})
return NextResponse.json({ keys }, { status: 200 })
} catch (error) {
return NextResponse.json({ error: 'Failed to get keys' }, { status: 500 })
}
})
export const DELETE = withRouteHandler(async (request: NextRequest) => {
try {
const session = await getSession()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = session.user.id
const mothershipBaseURL = await getMothershipBaseURL({ userId })
const queryResult = deleteCopilotApiKeyQuerySchema.safeParse(
Object.fromEntries(new URL(request.url).searchParams)
)
if (!queryResult.success) {
return NextResponse.json({ error: 'id is required' }, { status: 400 })
}
const { id } = queryResult.data
const res = await fetchGo(`${mothershipBaseURL}/api/validate-key/delete`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(env.COPILOT_API_KEY ? { 'x-api-key': env.COPILOT_API_KEY } : {}),
},
body: JSON.stringify({ userId, apiKeyId: id }),
spanName: 'sim → go /api/validate-key/delete',
operation: 'delete_api_key',
attributes: { [TraceAttr.UserId]: userId, [TraceAttr.ApiKeyId]: id },
})
if (!res.ok) {
return NextResponse.json({ error: 'Failed to delete key' }, { status: res.status || 500 })
}
const data = (await res.json().catch(() => null)) as { success?: boolean } | null
if (!data?.success) {
return NextResponse.json({ error: 'Invalid response from Sim Agent' }, { status: 500 })
}
return NextResponse.json({ success: true }, { status: 200 })
} catch (error) {
return NextResponse.json({ error: 'Failed to delete key' }, { status: 500 })
}
})
@@ -0,0 +1,114 @@
/**
* @vitest-environment node
*/
import { createMockRequest } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockFlags,
mockDbLimit,
mockCheckInternalApiKey,
mockCheckServerSideUsageLimits,
mockCheckOrgMemberUsageLimit,
} = vi.hoisted(() => ({
mockFlags: { isHosted: true },
mockDbLimit: vi.fn(),
mockCheckInternalApiKey: vi.fn(),
mockCheckServerSideUsageLimits: vi.fn(),
mockCheckOrgMemberUsageLimit: vi.fn(),
}))
vi.mock('@sim/db', () => ({
db: {
select: () => ({ from: () => ({ where: () => ({ limit: mockDbLimit }) }) }),
},
}))
vi.mock('@/lib/billing/calculations/usage-monitor', () => ({
checkServerSideUsageLimits: mockCheckServerSideUsageLimits,
checkOrgMemberUsageLimit: mockCheckOrgMemberUsageLimit,
}))
vi.mock('@/lib/copilot/request/http', () => ({
checkInternalApiKey: mockCheckInternalApiKey,
}))
vi.mock('@/lib/copilot/request/otel', () => ({
withIncomingGoSpan: (
_headers: unknown,
_span: unknown,
_attrs: unknown,
fn: (span: { setAttribute: () => void; setAttributes: () => void }) => unknown
) => fn({ setAttribute: vi.fn(), setAttributes: vi.fn() }),
}))
vi.mock('@/lib/core/config/env-flags', () => ({
get isHosted() {
return mockFlags.isHosted
},
}))
import { POST } from '@/app/api/copilot/api-keys/validate/route'
function request(body: Record<string, unknown>) {
return createMockRequest('POST', body, { 'x-api-key': 'internal' })
}
describe('POST /api/copilot/api-keys/validate — per-member enforcement', () => {
beforeEach(() => {
vi.clearAllMocks()
mockFlags.isHosted = true
mockCheckInternalApiKey.mockReturnValue({ success: true })
mockDbLimit.mockResolvedValue([{ id: 'user-1' }])
mockCheckServerSideUsageLimits.mockResolvedValue({
isExceeded: false,
currentUsage: 0,
limit: 100,
})
mockCheckOrgMemberUsageLimit.mockResolvedValue({
isExceeded: false,
currentUsage: 0,
limit: null,
})
})
it('returns 402 when the pooled/personal limit is exceeded (existing behavior)', async () => {
mockCheckServerSideUsageLimits.mockResolvedValue({
isExceeded: true,
currentUsage: 200,
limit: 100,
})
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(402)
expect(mockCheckOrgMemberUsageLimit).not.toHaveBeenCalled()
})
it('returns 402 when the per-member org-workspace cap is exceeded', async () => {
mockCheckOrgMemberUsageLimit.mockResolvedValue({
isExceeded: true,
currentUsage: 5,
limit: 4,
})
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(402)
expect(mockCheckOrgMemberUsageLimit).toHaveBeenCalledWith('user-1', 'ws-1')
})
it('returns 200 when under both limits', async () => {
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(200)
})
it('rejects with 400 when workspaceId is omitted (contract-required, fail closed)', async () => {
const res = await POST(request({ userId: 'user-1' }))
expect(res.status).toBe(400)
expect(mockCheckOrgMemberUsageLimit).not.toHaveBeenCalled()
})
it('skips the per-member check when not hosted', async () => {
mockFlags.isHosted = false
const res = await POST(request({ userId: 'user-1', workspaceId: 'ws-1' }))
expect(res.status).toBe(200)
expect(mockCheckOrgMemberUsageLimit).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,144 @@
import { db } from '@sim/db'
import { user } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { validateCopilotApiKeyContract } from '@/lib/api/contracts/copilot'
import { parseRequest, validationErrorResponse } from '@/lib/api/server'
import {
checkOrgMemberUsageLimit,
checkServerSideUsageLimits,
} from '@/lib/billing/calculations/usage-monitor'
import { CopilotValidateOutcome } from '@/lib/copilot/generated/trace-attribute-values-v1'
import { TraceAttr } from '@/lib/copilot/generated/trace-attributes-v1'
import { TraceSpan } from '@/lib/copilot/generated/trace-spans-v1'
import { checkInternalApiKey } from '@/lib/copilot/request/http'
import { withIncomingGoSpan } from '@/lib/copilot/request/otel'
import { isHosted } from '@/lib/core/config/env-flags'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
const logger = createLogger('CopilotApiKeysValidate')
/**
* Incoming-from-Go: extracts traceparent so this handler's work shows up as
* a child of the Go-side `sim.validate_api_key` span in the same trace. If
* there's no traceparent (manual curl / browser), the helper falls back to a
* new root span.
*/
export const POST = withRouteHandler((req: NextRequest) =>
withIncomingGoSpan(
req.headers,
TraceSpan.CopilotAuthValidateApiKey,
{
[TraceAttr.HttpMethod]: 'POST',
[TraceAttr.HttpRoute]: '/api/copilot/api-keys/validate',
},
async (span) => {
try {
const auth = checkInternalApiKey(req)
if (!auth.success) {
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.InternalAuthFailed
)
span.setAttribute(TraceAttr.HttpStatusCode, 401)
return new NextResponse(null, { status: 401 })
}
const parsed = await parseRequest(
validateCopilotApiKeyContract,
req,
{},
{
validationErrorResponse: (error) => {
logger.warn('Invalid validation request', { errors: error.issues })
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.InvalidBody
)
span.setAttribute(TraceAttr.HttpStatusCode, 400)
return validationErrorResponse(error, 'userId is required')
},
invalidJsonResponse: () => {
logger.warn('Invalid validation request: invalid JSON')
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.InvalidBody
)
span.setAttribute(TraceAttr.HttpStatusCode, 400)
return NextResponse.json(
{ error: 'userId is required', details: [] },
{ status: 400 }
)
},
}
)
if (!parsed.success) return parsed.response
const { userId, workspaceId } = parsed.data.body
span.setAttribute(TraceAttr.UserId, userId)
const [existingUser] = await db.select().from(user).where(eq(user.id, userId)).limit(1)
if (!existingUser) {
logger.warn('[API VALIDATION] userId does not exist', { userId })
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.UserNotFound)
span.setAttribute(TraceAttr.HttpStatusCode, 403)
return NextResponse.json({ error: 'User not found' }, { status: 403 })
}
logger.info('[API VALIDATION] Validating usage limit', { userId })
const { isExceeded, currentUsage, limit } = await checkServerSideUsageLimits(userId)
span.setAttributes({
[TraceAttr.BillingUsageCurrent]: currentUsage,
[TraceAttr.BillingUsageLimit]: limit,
[TraceAttr.BillingUsageExceeded]: isExceeded,
})
logger.info('[API VALIDATION] Usage limit validated', {
userId,
currentUsage,
limit,
isExceeded,
})
if (isExceeded) {
logger.info('[API VALIDATION] Usage exceeded', { userId, currentUsage, limit })
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.UsageExceeded)
span.setAttribute(TraceAttr.HttpStatusCode, 402)
return new NextResponse(null, { status: 402 })
}
// Per-member org-workspace cap (hosted-only). Blocks the mothership/copilot
// chat request itself when the user is over their personal credit limit for
// the org that owns this workspace, independent of the pooled org limit.
// workspaceId is contract-required, so the gate can't be silently skipped.
if (isHosted) {
const memberCheck = await checkOrgMemberUsageLimit(userId, workspaceId)
if (memberCheck.isExceeded) {
logger.info('[API VALIDATION] Per-member org usage limit exceeded', {
userId,
workspaceId,
currentUsage: memberCheck.currentUsage,
limit: memberCheck.limit,
})
span.setAttribute(
TraceAttr.CopilotValidateOutcome,
CopilotValidateOutcome.UsageExceeded
)
span.setAttribute(TraceAttr.HttpStatusCode, 402)
return new NextResponse(null, { status: 402 })
}
}
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.Ok)
span.setAttribute(TraceAttr.HttpStatusCode, 200)
return new NextResponse(null, { status: 200 })
} catch (error) {
logger.error('Error validating usage limit', { error })
span.setAttribute(TraceAttr.CopilotValidateOutcome, CopilotValidateOutcome.InternalError)
span.setAttribute(TraceAttr.HttpStatusCode, 500)
return NextResponse.json({ error: 'Failed to validate usage' }, { status: 500 })
}
}
)
)