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
+121
View File
@@ -0,0 +1,121 @@
import { db } from '@sim/db'
import { settings, user } from '@sim/db/schema'
import { getErrorMessage } from '@sim/utils/errors'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import {
deleteCopilotByokKeyContract,
listCopilotByokKeysContract,
upsertCopilotByokKeyContract,
} from '@/lib/api/contracts/copilot'
import { parseRequest } from '@/lib/api/server'
import { getSession } from '@/lib/auth'
import { SIM_AGENT_API_URL } from '@/lib/copilot/constants'
import { getMothershipSourceEnvHeaders } from '@/lib/copilot/server/agent-url'
import { env } from '@/lib/core/config/env'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
/**
* Enterprise BYOK key management for the current workspace's mothership.
*
* Unlike the cross-environment admin inspector (`/api/admin/mothership`), this
* talks to the SAME copilot the workspace's mothership actually runs on —
* `SIM_AGENT_API_URL` (local in dev, prod copilot in prod) — and authenticates
* with the hosted internal key (`COPILOT_API_KEY`), the exact credential
* mothership chat uses. Copilot requires that key (`SIM_AGENT_API_KEY`) and
* rejects self-hosted callers, so BYOK can only ever be written through our
* hosted Sim. The route is superuser-gated; the workspace id rides in the
* request and is resolved by the caller from the route.
*/
async function getAuthorizedSuperUserId(): Promise<string | null> {
const session = await getSession()
if (!session?.user?.id) return null
const [currentUser] = await db
.select({ role: user.role, superUserModeEnabled: settings.superUserModeEnabled })
.from(user)
.leftJoin(settings, eq(settings.userId, user.id))
.where(eq(user.id, session.user.id))
.limit(1)
const authorized = currentUser?.role === 'admin' && (currentUser.superUserModeEnabled ?? false)
return authorized ? session.user.id : null
}
async function forwardToCopilot(
method: 'GET' | 'POST' | 'DELETE',
query: URLSearchParams,
body?: string
) {
const headers: Record<string, string> = { ...getMothershipSourceEnvHeaders() }
if (env.COPILOT_API_KEY) headers['x-api-key'] = env.COPILOT_API_KEY
if (body !== undefined) headers['Content-Type'] = 'application/json'
const qs = query.toString()
const targetUrl = `${SIM_AGENT_API_URL}/api/admin/byok${qs ? `?${qs}` : ''}`
try {
const upstream = await fetch(targetUrl, {
method,
headers,
...(body !== undefined ? { body } : {}),
})
const text = await upstream.text()
// boundary-raw-fetch: copilot returns JSON; tolerate an empty body.
const data = text ? JSON.parse(text) : {}
return NextResponse.json(data, { status: upstream.status })
} catch (error) {
return NextResponse.json(
{ error: `Failed to reach copilot: ${getErrorMessage(error, 'Unknown error')}` },
{ status: 502 }
)
}
}
export const GET = withRouteHandler(async (req: NextRequest) => {
const userId = await getAuthorizedSuperUserId()
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(listCopilotByokKeysContract, req, {})
if (!parsed.success) return parsed.response
return forwardToCopilot(
'GET',
new URLSearchParams({ workspaceId: parsed.data.query.workspaceId })
)
})
export const POST = withRouteHandler(async (req: NextRequest) => {
const userId = await getAuthorizedSuperUserId()
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(upsertCopilotByokKeyContract, req, {})
if (!parsed.success) return parsed.response
// Bind the audit field to the authenticated superuser, ignoring any
// client-supplied createdBy so provisioning is always attributable.
const body = JSON.stringify({ ...parsed.data.body, createdBy: userId })
return forwardToCopilot('POST', new URLSearchParams(), body)
})
export const DELETE = withRouteHandler(async (req: NextRequest) => {
const userId = await getAuthorizedSuperUserId()
if (!userId) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const parsed = await parseRequest(deleteCopilotByokKeyContract, req, {})
if (!parsed.success) return parsed.response
return forwardToCopilot(
'DELETE',
new URLSearchParams({
workspaceId: parsed.data.query.workspaceId,
provider: parsed.data.query.provider,
})
)
})
@@ -0,0 +1,68 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { validateCopilotByokContract } from '@/lib/api/contracts/copilot'
import { parseRequest } from '@/lib/api/server'
import { isWorkspaceOnEnterprisePlan } from '@/lib/billing/core/subscription'
import { checkInternalApiKey } from '@/lib/copilot/request/http'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { verifyEffectiveSuperUser } from '@/lib/permissions/super-user'
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
const logger = createLogger('CopilotByokValidate')
/**
* Authoritative entitlement gate for enterprise BYOK, called server-to-server by
* the mothership (Go) before it uses a workspace's own provider key. Gated by
* INTERNAL_API_SECRET — never exposed to the browser.
*
* Returns 200 when EITHER:
* - the requesting user is a superuser admin (platform admin with superuser
* mode on), who may use BYOK on any workspace for management/testing; OR
* - the user is a member of the workspace (prevents one org from causing
* another org's stored key to be used) AND the workspace is on an
* enterprise plan.
*
* Any other case returns 403 (not entitled) or 401 (bad internal auth). The Go
* caller fails closed to hosted keys on anything but a 200.
*/
export const POST = withRouteHandler(async (req: NextRequest) => {
const auth = checkInternalApiKey(req)
if (!auth.success) {
return new NextResponse(null, { status: 401 })
}
const parsed = await parseRequest(validateCopilotByokContract, req, {})
if (!parsed.success) return parsed.response
const { workspaceId, userId } = parsed.data.body
try {
// Superuser admins may use BYOK on any workspace (management/testing).
const { effectiveSuperUser } = await verifyEffectiveSuperUser(userId)
if (effectiveSuperUser) {
return new NextResponse(null, { status: 200 })
}
// Everyone else must be a workspace member on an enterprise plan. The
// membership check prevents one org from using another org's stored key.
const permission = await getUserEntityPermissions(userId, 'workspace', workspaceId)
if (!permission) {
logger.warn('BYOK validate denied: user is not a member of the workspace', {
workspaceId,
userId,
})
return new NextResponse(null, { status: 403 })
}
const eligible = await isWorkspaceOnEnterprisePlan(workspaceId)
if (!eligible) {
logger.warn('BYOK validate denied: workspace is not on an enterprise plan', { workspaceId })
return new NextResponse(null, { status: 403 })
}
return new NextResponse(null, { status: 200 })
} catch (error) {
logger.error('BYOK validation failed', { error, workspaceId })
return NextResponse.json({ error: 'Failed to validate BYOK entitlement' }, { status: 500 })
}
})