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
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:
@@ -0,0 +1,125 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { getValidationErrorMessage, isZodError } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import {
|
||||
assertSafeZoomInfoUrl,
|
||||
extractZoomInfoError,
|
||||
fetchZoomInfoAccessToken,
|
||||
ZOOMINFO_API_BASE,
|
||||
ZOOMINFO_OUTBOUND_FETCH_TIMEOUT_MS,
|
||||
type ZoomInfoProxyRequest,
|
||||
ZoomInfoProxyRequestSchema,
|
||||
} from '@/app/api/tools/zoominfo/shared'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('ZoomInfoProxyAPI')
|
||||
|
||||
function buildApiUrl(req: ZoomInfoProxyRequest): string {
|
||||
const subPath = req.path.startsWith('/') ? req.path : `/${req.path}`
|
||||
const url = `${ZOOMINFO_API_BASE}${subPath}`
|
||||
|
||||
if (!req.query || Object.keys(req.query).length === 0) {
|
||||
return url
|
||||
}
|
||||
const search = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(req.query)) {
|
||||
if (value === undefined || value === null) continue
|
||||
search.append(key, String(value))
|
||||
}
|
||||
const queryString = search.toString()
|
||||
if (!queryString) return url
|
||||
return url.includes('?') ? `${url}&${queryString}` : `${url}?${queryString}`
|
||||
}
|
||||
|
||||
interface Invocation {
|
||||
status: number
|
||||
body: unknown
|
||||
}
|
||||
|
||||
async function callZoomInfo(req: ZoomInfoProxyRequest, accessToken: string): Promise<Invocation> {
|
||||
const url = assertSafeZoomInfoUrl(buildApiUrl(req), 'apiUrl').toString()
|
||||
const hasBody = req.body !== undefined && req.body !== null
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
}
|
||||
if (hasBody) headers['Content-Type'] = 'application/json'
|
||||
|
||||
const response = await secureFetchWithValidation(
|
||||
url,
|
||||
{
|
||||
method: req.method,
|
||||
headers,
|
||||
body: hasBody
|
||||
? typeof req.body === 'string'
|
||||
? req.body
|
||||
: JSON.stringify(req.body)
|
||||
: undefined,
|
||||
timeout: ZOOMINFO_OUTBOUND_FETCH_TIMEOUT_MS,
|
||||
},
|
||||
'apiUrl'
|
||||
)
|
||||
|
||||
const raw = await response.text()
|
||||
let parsed: unknown = null
|
||||
if (raw.length > 0) {
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
parsed = raw
|
||||
}
|
||||
}
|
||||
return { status: response.status, body: parsed }
|
||||
}
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
||||
if (!authResult.success) {
|
||||
logger.warn(`[${requestId}] Unauthorized ZoomInfo proxy request: ${authResult.error}`)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authResult.error || 'Authentication required' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
// boundary-raw-json: internal proxy envelope validated by ZoomInfoProxyRequestSchema below; not a public boundary
|
||||
const json = await request.json()
|
||||
const proxyReq = ZoomInfoProxyRequestSchema.parse(json)
|
||||
|
||||
const accessToken = await fetchZoomInfoAccessToken(proxyReq, requestId)
|
||||
const invocation = await callZoomInfo(proxyReq, accessToken)
|
||||
|
||||
if (invocation.status >= 200 && invocation.status < 300) {
|
||||
const data = invocation.status === 204 ? null : invocation.body
|
||||
return NextResponse.json({ success: true, output: { status: invocation.status, data } })
|
||||
}
|
||||
|
||||
const message = extractZoomInfoError(invocation.body, invocation.status)
|
||||
logger.warn(
|
||||
`[${requestId}] ZoomInfo API error (${invocation.status}) ${proxyReq.path}: ${message}`
|
||||
)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: message, status: invocation.status },
|
||||
{ status: invocation.status }
|
||||
)
|
||||
} catch (error) {
|
||||
if (isZodError(error)) {
|
||||
logger.warn(`[${requestId}] Validation error:`, error.issues)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: getValidationErrorMessage(error, 'Validation failed') },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
logger.error(`[${requestId}] Unexpected ZoomInfo proxy error:`, error)
|
||||
return NextResponse.json({ success: false, error: toError(error).message }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,204 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { z } from 'zod'
|
||||
import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server'
|
||||
|
||||
const logger = createLogger('ZoomInfoShared')
|
||||
|
||||
export const ZOOMINFO_API_BASE = 'https://api.zoominfo.com/gtm'
|
||||
export const ZOOMINFO_TOKEN_URL = `${ZOOMINFO_API_BASE}/oauth/v1/token`
|
||||
export const ZOOMINFO_OUTBOUND_FETCH_TIMEOUT_MS = 30_000
|
||||
|
||||
export const ZoomInfoAuthSchema = z.object({
|
||||
clientId: z.string().min(1, 'clientId is required'),
|
||||
clientSecret: z.string().min(1, 'clientSecret is required'),
|
||||
})
|
||||
|
||||
export type ZoomInfoAuth = z.infer<typeof ZoomInfoAuthSchema>
|
||||
|
||||
export const ZoomInfoHttpMethod = z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
|
||||
|
||||
export const ZoomInfoProxyPath = z
|
||||
.string()
|
||||
.min(1, 'path is required')
|
||||
.refine(
|
||||
(p) =>
|
||||
!p.split(/[/\\]/).some((seg) => seg === '..' || seg === '.') &&
|
||||
!p.includes('#') &&
|
||||
!/%(?:2[eEfF]|5[cC]|23)/.test(p),
|
||||
{
|
||||
message:
|
||||
'path must not contain ".." or "." segments, "#", or percent-encoded path/fragment characters',
|
||||
}
|
||||
)
|
||||
|
||||
export const ZoomInfoProxyRequestSchema = ZoomInfoAuthSchema.extend({
|
||||
path: ZoomInfoProxyPath,
|
||||
method: ZoomInfoHttpMethod.default('POST'),
|
||||
query: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
|
||||
body: z.unknown().optional(),
|
||||
})
|
||||
|
||||
export type ZoomInfoProxyRequest = z.infer<typeof ZoomInfoProxyRequestSchema>
|
||||
|
||||
const FORBIDDEN_HOSTS = new Set([
|
||||
'localhost',
|
||||
'0.0.0.0',
|
||||
'127.0.0.1',
|
||||
'169.254.169.254',
|
||||
'metadata.google.internal',
|
||||
'metadata',
|
||||
'[::1]',
|
||||
'[::]',
|
||||
])
|
||||
|
||||
function isPrivateIPv4(host: string): boolean {
|
||||
const match = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
|
||||
if (!match) return false
|
||||
const octets = match.slice(1, 5).map(Number) as [number, number, number, number]
|
||||
if (octets.some((o) => o < 0 || o > 255)) return false
|
||||
const [a, b] = octets
|
||||
if (a === 10) return true
|
||||
if (a === 172 && b >= 16 && b <= 31) return true
|
||||
if (a === 192 && b === 168) return true
|
||||
if (a === 127) return true
|
||||
if (a === 169 && b === 254) return true
|
||||
if (a === 0) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export function assertSafeZoomInfoUrl(rawUrl: string, label: string): URL {
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(rawUrl)
|
||||
} catch {
|
||||
throw new Error(`${label} must be a valid URL`)
|
||||
}
|
||||
if (parsed.protocol !== 'https:') {
|
||||
throw new Error(`${label} must use https://`)
|
||||
}
|
||||
const host = parsed.hostname.toLowerCase()
|
||||
if (FORBIDDEN_HOSTS.has(host)) {
|
||||
throw new Error(`${label} host is not allowed`)
|
||||
}
|
||||
if (isPrivateIPv4(host)) {
|
||||
throw new Error(`${label} host is not allowed (private/loopback range)`)
|
||||
}
|
||||
if (host !== 'api.zoominfo.com') {
|
||||
throw new Error(`${label} host must be api.zoominfo.com`)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
interface CachedToken {
|
||||
accessToken: string
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const TOKEN_CACHE = new Map<string, CachedToken>()
|
||||
const TOKEN_CACHE_MAX_ENTRIES = 500
|
||||
const TOKEN_SAFETY_WINDOW_MS = 60_000
|
||||
|
||||
function tokenCacheKey(auth: ZoomInfoAuth): string {
|
||||
const secretHash = createHash('sha256').update(auth.clientSecret).digest('hex').slice(0, 16)
|
||||
return `${auth.clientId}::${secretHash}`
|
||||
}
|
||||
|
||||
function rememberToken(key: string, token: CachedToken): void {
|
||||
if (TOKEN_CACHE.has(key)) TOKEN_CACHE.delete(key)
|
||||
TOKEN_CACHE.set(key, token)
|
||||
while (TOKEN_CACHE.size > TOKEN_CACHE_MAX_ENTRIES) {
|
||||
const oldestKey = TOKEN_CACHE.keys().next().value
|
||||
if (oldestKey === undefined) break
|
||||
TOKEN_CACHE.delete(oldestKey)
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchZoomInfoAccessToken(
|
||||
auth: ZoomInfoAuth,
|
||||
requestId: string
|
||||
): Promise<string> {
|
||||
const cacheKey = tokenCacheKey(auth)
|
||||
const cached = TOKEN_CACHE.get(cacheKey)
|
||||
if (cached && cached.expiresAt - TOKEN_SAFETY_WINDOW_MS > Date.now()) {
|
||||
return cached.accessToken
|
||||
}
|
||||
|
||||
const tokenUrl = assertSafeZoomInfoUrl(ZOOMINFO_TOKEN_URL, 'tokenUrl').toString()
|
||||
const basic = Buffer.from(`${auth.clientId}:${auth.clientSecret}`).toString('base64')
|
||||
|
||||
const params = new URLSearchParams()
|
||||
params.set('grant_type', 'client_credentials')
|
||||
|
||||
const response = await secureFetchWithValidation(
|
||||
tokenUrl,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Basic ${basic}`,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: params.toString(),
|
||||
timeout: ZOOMINFO_OUTBOUND_FETCH_TIMEOUT_MS,
|
||||
},
|
||||
'tokenUrl'
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => '')
|
||||
logger.warn(`[${requestId}] ZoomInfo token fetch failed (${response.status}): ${text}`)
|
||||
throw new Error(`ZoomInfo token request failed: HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
access_token?: string
|
||||
expires_in?: number
|
||||
}
|
||||
|
||||
if (!data.access_token) {
|
||||
throw new Error('ZoomInfo token response missing access_token')
|
||||
}
|
||||
|
||||
const expiresInMs = (data.expires_in ?? 3300) * 1000
|
||||
rememberToken(cacheKey, {
|
||||
accessToken: data.access_token,
|
||||
expiresAt: Date.now() + expiresInMs,
|
||||
})
|
||||
return data.access_token
|
||||
}
|
||||
|
||||
export function extractZoomInfoError(body: unknown, status: number): string {
|
||||
if (body && typeof body === 'object') {
|
||||
const obj = body as Record<string, unknown>
|
||||
if (obj.error && typeof obj.error === 'object') {
|
||||
const eo = obj.error as Record<string, unknown>
|
||||
const message = typeof eo.message === 'string' ? eo.message : ''
|
||||
const code = typeof eo.code === 'string' ? eo.code : ''
|
||||
if (message) return code ? `[${code}] ${message}` : message
|
||||
}
|
||||
if (typeof obj.error === 'string' && obj.error.length > 0) {
|
||||
const desc = typeof obj.error_description === 'string' ? `: ${obj.error_description}` : ''
|
||||
return `${obj.error}${desc}`
|
||||
}
|
||||
if (typeof obj.message === 'string' && obj.message.length > 0) {
|
||||
return obj.message
|
||||
}
|
||||
if (Array.isArray(obj.errors) && obj.errors.length > 0) {
|
||||
return obj.errors
|
||||
.map((e) => {
|
||||
if (e && typeof e === 'object') {
|
||||
const eo = e as Record<string, unknown>
|
||||
const title = typeof eo.title === 'string' ? eo.title : ''
|
||||
const detail = typeof eo.detail === 'string' ? `: ${eo.detail}` : ''
|
||||
return `${title}${detail}`.trim()
|
||||
}
|
||||
return String(e)
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join('; ')
|
||||
}
|
||||
}
|
||||
if (typeof body === 'string' && body.length > 0) return body
|
||||
return `ZoomInfo request failed with HTTP ${status}`
|
||||
}
|
||||
Reference in New Issue
Block a user