Repository navigation
Expand file tree
/
Copy pathserver.mjs
More file actions
860 lines (736 loc) · 26.2 KB
/
Copy pathserver.mjs
File metadata and controls
860 lines (736 loc) · 26.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
import http from 'node:http'
import { createHash, createHmac } from 'node:crypto'
import { createWriteStream, existsSync, readFileSync } from 'node:fs'
import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { fetch as undiciFetch, ProxyAgent } from 'undici'
loadLocalEnv()
const API_PORT = Number(process.env.API_PORT || 8787)
const BODY_LIMIT = 28 * 1024 * 1024
const MODEL_UPLOAD_LIMIT = 180 * 1024 * 1024
const TRIPO_API_KEY = process.env.TRIPO_API_KEY
const TRIPO_API_BASE = process.env.TRIPO_API_BASE || 'https://api.tripo3d.ai/v2/openapi'
const TRIPO_MODEL_VERSION = process.env.TRIPO_MODEL_VERSION || 'v3.0-20250812'
const HUNYUAN_API_BASE = process.env.HUNYUAN_API_BASE || 'http://127.0.0.1:8081'
const HUNYUAN_CREATE_PATH = process.env.HUNYUAN_CREATE_PATH || '/send'
const HUNYUAN_STATUS_PATH = process.env.HUNYUAN_STATUS_PATH || '/status'
const LOCAL_MODEL_DIR = path.resolve(process.env.LOCAL_MODEL_DIR || '.generated-models')
const OUTBOUND_PROXY_AGENT = createProxyAgent()
const server = http.createServer(async (request, response) => {
try {
setCorsHeaders(response)
if (request.method === 'OPTIONS') {
response.writeHead(204)
response.end()
return
}
const url = new URL(request.url, `http://${request.headers.host}`)
if (request.method === 'GET' && url.pathname === '/api/3d/health') {
sendJson(response, 200, {
ok: true,
providers: {
tripo: {
configured: Boolean(TRIPO_API_KEY),
modelVersion: TRIPO_MODEL_VERSION,
},
hunyuan: {
configured: Boolean(HUNYUAN_API_BASE),
baseUrl: HUNYUAN_API_BASE,
createPath: HUNYUAN_CREATE_PATH,
statusPath: HUNYUAN_STATUS_PATH,
},
},
})
return
}
if (request.method === 'POST' && url.pathname === '/api/3d/generate') {
const payload = await readJsonBody(request)
const provider = payload.provider || 'tripo'
if (provider === 'hunyuan') {
const task = await createHunyuanTask(payload)
sendJson(response, 200, task)
return
}
requireTripoKey()
const image = parseDataUrl(payload.imageDataUrl)
const fileName = sanitizeFileName(payload.fileName || `cell-reference.${image.ext}`)
const file = await uploadImageToTripo({ ...image, fileName })
const task = await createTripoImageTask({
file,
})
sendJson(response, 200, {
provider: 'tripo',
taskId: task.taskId,
raw: task.raw,
})
return
}
if (request.method === 'GET' && url.pathname.startsWith('/api/3d/status/')) {
const taskId = decodeURIComponent(url.pathname.replace('/api/3d/status/', ''))
const provider = url.searchParams.get('provider') || 'tripo'
if (provider === 'hunyuan') {
const task = await getHunyuanTask(taskId)
sendJson(response, 200, task)
return
}
requireTripoKey()
const task = await getTripoTask(taskId)
sendJson(response, 200, task)
return
}
if (request.method === 'GET' && url.pathname === '/api/3d/model') {
await proxyModel(url, response)
return
}
if (request.method === 'POST' && url.pathname === '/api/3d/local-model') {
const model = await importLocalModel(request, url)
sendJson(response, 200, model)
return
}
if (request.method === 'GET' && url.pathname.startsWith('/api/3d/local-model/')) {
await serveLocalModel(url, response)
return
}
sendJson(response, 404, { error: 'Not found' })
} catch (error) {
if (response.headersSent) {
response.destroy(error)
return
}
const status = error.status || 500
sendJson(response, status, {
error: error.message || 'Server error',
detail: error.detail,
})
}
})
server.listen(API_PORT, () => {
console.log(`Bio demo API running at http://127.0.0.1:${API_PORT}`)
console.log(TRIPO_API_KEY ? 'Tripo API key loaded from environment.' : 'TRIPO_API_KEY is missing. Add it to .env.local.')
console.log(`Hunyuan3D local provider: ${HUNYUAN_API_BASE}`)
})
function loadLocalEnv() {
if (!existsSync('.env.local')) return
const env = readFileSync('.env.local', 'utf8')
for (const line of env.split(/\r?\n/)) {
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith('#')) continue
const index = trimmed.indexOf('=')
if (index === -1) continue
const key = trimmed.slice(0, index).trim()
let value = trimmed.slice(index + 1).trim()
value = value.replace(/^["']|["']$/g, '')
if (!process.env[key]) process.env[key] = value
}
}
function createProxyAgent() {
const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy
if (!proxy) return null
return new ProxyAgent(proxy)
}
function setCorsHeaders(response) {
response.setHeader('Access-Control-Allow-Origin', process.env.CORS_ORIGIN || '*')
response.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
response.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization')
}
function sendJson(response, status, payload) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' })
response.end(JSON.stringify(payload))
}
function requireTripoKey() {
if (!TRIPO_API_KEY) {
const error = new Error('TRIPO_API_KEY is not configured on the backend.')
error.status = 500
throw error
}
}
function readJsonBody(request) {
return new Promise((resolve, reject) => {
const chunks = []
let size = 0
request.on('data', (chunk) => {
size += chunk.length
if (size > BODY_LIMIT) {
reject(Object.assign(new Error('Image payload is too large.'), { status: 413 }))
request.destroy()
return
}
chunks.push(chunk)
})
request.on('end', () => {
try {
const raw = Buffer.concat(chunks).toString('utf8')
resolve(raw ? JSON.parse(raw) : {})
} catch {
reject(Object.assign(new Error('Invalid JSON payload.'), { status: 400 }))
}
})
request.on('error', reject)
})
}
function readRawBody(request, limit = MODEL_UPLOAD_LIMIT) {
return new Promise((resolve, reject) => {
const chunks = []
let size = 0
request.on('data', (chunk) => {
size += chunk.length
if (size > limit) {
reject(Object.assign(new Error('Model payload is too large.'), { status: 413 }))
request.destroy()
return
}
chunks.push(chunk)
})
request.on('end', () => {
resolve(Buffer.concat(chunks))
})
request.on('error', reject)
})
}
function parseDataUrl(dataUrl) {
if (typeof dataUrl !== 'string') {
throw Object.assign(new Error('imageDataUrl is required.'), { status: 400 })
}
const match = dataUrl.match(/^data:(image\/(?:png|jpe?g|webp));base64,(.+)$/)
if (!match) {
throw Object.assign(new Error('Only PNG, JPEG, or WebP image data URLs are supported.'), { status: 400 })
}
const mime = match[1]
const buffer = Buffer.from(match[2], 'base64')
const ext = mime.includes('png') ? 'png' : mime.includes('webp') ? 'webp' : 'jpg'
if (buffer.length < 1024) {
throw Object.assign(new Error('Image is too small for 3D generation.'), { status: 400 })
}
return { mime, buffer, ext }
}
function sanitizeFileName(fileName) {
return fileName.replace(/[^\w.\- ]+/g, '').trim() || 'cell-reference.png'
}
async function uploadImageToTripo({ buffer, mime, fileName }) {
const format = getTripoUploadFormat(fileName, mime)
const tokenResult = await tripoRequest('/upload/sts/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ format }),
})
const tokenData = tokenResult.data || tokenResult
const host = tokenData.s3_host
const bucket = tokenData.resource_bucket
const key = tokenData.resource_uri
if (!host || !bucket || !key || !tokenData.sts_ak || !tokenData.sts_sk || !tokenData.session_token) {
const error = new Error('Tripo STS upload token response is missing required fields.')
error.detail = sanitizeTripoRaw(tokenResult)
throw error
}
await uploadToTripoObjectStorage({
buffer,
mime,
host,
bucket,
key,
accessKeyId: tokenData.sts_ak,
secretAccessKey: tokenData.sts_sk,
sessionToken: tokenData.session_token,
})
return {
type: 'jpg',
object: {
bucket,
key,
},
}
}
async function createTripoImageTask({ file }) {
const payload = {
type: 'image_to_model',
model_version: TRIPO_MODEL_VERSION,
file,
texture: true,
pbr: true,
texture_quality: 'standard',
geometry_quality: 'standard',
enable_image_autofix: true,
}
try {
return normalizeTaskCreateResponse(await tripoRequest('/task', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
}))
} catch {
const minimalPayload = {
type: 'image_to_model',
file,
}
return normalizeTaskCreateResponse(await tripoRequest('/task', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(minimalPayload),
}))
}
}
function getTripoUploadFormat(fileName, mime) {
const ext = path.extname(fileName).replace('.', '').toLowerCase()
if (ext === 'png' || mime === 'image/png') return 'png'
if (ext === 'webp' || mime === 'image/webp') return 'webp'
return 'jpeg'
}
async function uploadToTripoObjectStorage({ buffer, mime, host, bucket, key, accessKeyId, secretAccessKey, sessionToken }) {
const region = getAwsRegionFromS3Host(host)
const amzDate = getAwsDate()
const date = amzDate.slice(0, 8)
const payloadHash = sha256Hex(buffer)
const canonicalUri = `/${bucket}/${encodeAwsPath(key)}`
const headers = {
'content-type': mime,
host,
'x-amz-content-sha256': payloadHash,
'x-amz-date': amzDate,
'x-amz-security-token': sessionToken,
}
const signedHeaderNames = Object.keys(headers).sort()
const signedHeaders = signedHeaderNames.join(';')
const canonicalHeaders = signedHeaderNames.map((name) => `${name}:${String(headers[name]).trim()}\n`).join('')
const canonicalRequest = ['PUT', canonicalUri, '', canonicalHeaders, signedHeaders, payloadHash].join('\n')
const credentialScope = `${date}/${region}/s3/aws4_request`
const stringToSign = ['AWS4-HMAC-SHA256', amzDate, credentialScope, sha256Hex(canonicalRequest)].join('\n')
const signingKey = hmac(hmac(hmac(hmac(`AWS4${secretAccessKey}`, date), region), 's3'), 'aws4_request')
const signature = createHmac('sha256', signingKey).update(stringToSign).digest('hex')
const fetchOptions = shouldUseProxy(`https://${host}`) && OUTBOUND_PROXY_AGENT ? { dispatcher: OUTBOUND_PROXY_AGENT } : {}
const response = await undiciFetch(`https://${host}${canonicalUri}`, {
method: 'PUT',
...fetchOptions,
headers: {
...headers,
authorization: `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
},
body: buffer,
})
if (!response.ok) {
const detail = await response.text().catch(() => '')
const error = new Error(`Tripo object upload failed with ${response.status}.`)
error.status = response.status || 502
error.detail = detail.slice(0, 500)
throw error
}
}
function getAwsRegionFromS3Host(host) {
return host.match(/s3[.-]([a-z0-9-]+)\./)?.[1] || 'us-west-2'
}
function getAwsDate(date = new Date()) {
return date.toISOString().replace(/[:-]|\.\d{3}/g, '')
}
function encodeAwsPath(value) {
return String(value).split('/').map((part) => encodeURIComponent(part)).join('/')
}
function sha256Hex(value) {
return createHash('sha256').update(value).digest('hex')
}
function hmac(key, value) {
return createHmac('sha256', key).update(value).digest()
}
function normalizeTaskCreateResponse(raw) {
const taskId = findFirstValue(raw, ['task_id', 'taskId', 'id'])
if (!taskId) {
const error = new Error('Tripo task response did not include a task id.')
error.detail = raw
throw error
}
return { taskId, raw }
}
async function getTripoTask(taskId) {
if (!taskId) {
throw Object.assign(new Error('taskId is required.'), { status: 400 })
}
if (await hasLocalModel(taskId, 'glb')) {
return {
provider: 'tripo',
taskId,
status: 'success',
progress: 100,
modelUrl: localModelUrl(taskId, 'glb'),
rawModelUrl: '',
error: '',
raw: { cached: true },
}
}
const raw = await tripoRequest(`/task/${encodeURIComponent(taskId)}`, { method: 'GET' })
const data = raw.data || raw
const status = data.status || data.task_status || data.state || 'unknown'
const rawModelUrl = findModelUrl(data)
let modelUrl = rawModelUrl ? `/api/3d/model?url=${encodeURIComponent(rawModelUrl)}` : ''
let cacheError = ''
if (rawModelUrl && isSuccessStatus(status)) {
try {
modelUrl = await cacheRemoteModel(taskId, rawModelUrl)
} catch (error) {
cacheError = error.message || 'Model cache failed.'
}
}
return {
provider: 'tripo',
taskId,
status,
progress: data.progress ?? data.percent ?? null,
modelUrl,
rawModelUrl,
error: data.error || cacheError || '',
raw,
}
}
async function createHunyuanTask(payload) {
const image = parseDataUrl(payload.imageDataUrl)
const imageBase64 = image.buffer.toString('base64')
const requestBody = {
image: `data:${image.mime};base64,${imageBase64}`,
image_base64: imageBase64,
prompt: payload.prompt || '',
seed: payload.seed ?? 1234,
remove_background: payload.removeBackground ?? true,
texture: payload.texture ?? true,
pbr: payload.pbr ?? true,
octree_resolution: payload.octreeResolution ?? 256,
num_inference_steps: payload.numInferenceSteps ?? 50,
guidance_scale: payload.guidanceScale ?? 5.5,
face_count: payload.faceCount ?? 60000,
}
const raw = await hunyuanRequest(HUNYUAN_CREATE_PATH, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody),
})
const data = raw.data || raw
const taskId = findFirstValue(data, ['uid', 'task_id', 'taskId', 'id']) || `hunyuan-${Date.now()}`
const rawModelUrl = findModelUrl(data)
const modelBase64 = findFirstValue(data, ['model_base64', 'modelBase64', 'glb_base64', 'glbBase64'])
let modelUrl = rawModelUrl ? `/api/3d/model?url=${encodeURIComponent(rawModelUrl)}` : ''
if (modelBase64) {
await saveLocalModel(taskId, modelBase64, 'glb')
modelUrl = localModelUrl(taskId, 'glb')
}
return {
provider: 'hunyuan',
taskId,
status: modelUrl ? 'success' : 'queued',
modelUrl,
raw: sanitizeHunyuanRaw(raw),
}
}
async function getHunyuanTask(taskId) {
if (!taskId) {
throw Object.assign(new Error('taskId is required.'), { status: 400 })
}
if (await hasLocalModel(taskId, 'glb')) {
return {
provider: 'hunyuan',
taskId,
status: 'success',
progress: 100,
modelUrl: localModelUrl(taskId, 'glb'),
rawModelUrl: '',
error: '',
raw: {},
}
}
const raw = await hunyuanRequest(`${HUNYUAN_STATUS_PATH}/${encodeURIComponent(taskId)}`, { method: 'GET' })
const data = raw.data || raw
const status = normalizeHunyuanStatus(data.status || data.task_status || data.state || data.message || 'running')
const progress = data.progress ?? data.percent ?? null
const rawModelUrl = findModelUrl(data)
const modelBase64 = findFirstValue(data, ['model_base64', 'modelBase64', 'glb_base64', 'glbBase64'])
let modelUrl = rawModelUrl ? `/api/3d/model?url=${encodeURIComponent(rawModelUrl)}` : ''
if (modelBase64) {
await saveLocalModel(taskId, modelBase64, 'glb')
modelUrl = localModelUrl(taskId, 'glb')
}
return {
provider: 'hunyuan',
taskId,
status,
progress,
modelUrl,
rawModelUrl,
error: data.error || data.message || '',
raw: sanitizeHunyuanRaw(raw),
}
}
async function hunyuanRequest(pathname, options = {}) {
let response
try {
response = await undiciFetch(`${HUNYUAN_API_BASE.replace(/\/$/, '')}${pathname.startsWith('/') ? pathname : `/${pathname}`}`, options)
} catch (error) {
const wrapped = new Error(`Hunyuan3D local server unavailable at ${HUNYUAN_API_BASE}. Start the local Hunyuan3D API server or switch provider.`)
wrapped.detail = {
path: pathname,
cause: error.cause?.message || error.cause?.code || error.message,
}
throw wrapped
}
const text = await response.text()
let data = {}
try {
data = text ? JSON.parse(text) : {}
} catch {
data = { message: text || 'Non-JSON response from Hunyuan3D.' }
}
if (!response.ok || (typeof data.code === 'number' && data.code !== 0)) {
const error = new Error(data.message || data.error || `Hunyuan3D request failed with ${response.status}.`)
error.status = response.status || 502
error.detail = sanitizeHunyuanRaw(data)
throw error
}
return data
}
function normalizeHunyuanStatus(status) {
const value = String(status || '').toLowerCase()
if (['success', 'succeeded', 'completed', 'complete', 'done', 'finish', 'finished'].includes(value)) return 'success'
if (['failed', 'error', 'cancelled', 'canceled'].includes(value)) return 'failed'
if (['queued', 'pending', 'waiting'].includes(value)) return 'queued'
return 'running'
}
function isSuccessStatus(status) {
return ['success', 'succeeded', 'completed', 'complete', 'done', 'finish', 'finished'].includes(String(status || '').toLowerCase())
}
function parseModelBase64(modelBase64) {
const raw = String(modelBase64 || '').replace(/^data:.*?;base64,/, '')
return Buffer.from(raw, 'base64')
}
async function saveLocalModel(taskId, modelData, ext = 'glb') {
const buffer = Buffer.isBuffer(modelData) ? modelData : parseModelBase64(modelData)
validateModelBuffer(buffer, ext)
await mkdir(LOCAL_MODEL_DIR, { recursive: true })
await writeFile(localModelPath(taskId, ext), buffer)
}
async function hasLocalModel(taskId, ext = 'glb') {
try {
await access(localModelPath(taskId, ext))
return true
} catch {
return false
}
}
function localModelPath(taskId, ext = 'glb') {
return path.join(LOCAL_MODEL_DIR, `${sanitizeModelId(taskId)}.${ext}`)
}
function localModelUrl(taskId, ext = 'glb') {
return `/api/3d/local-model/${encodeURIComponent(sanitizeModelId(taskId))}.${ext}`
}
async function serveLocalModel(url, response) {
const rawFileName = decodeURIComponent(url.pathname.replace('/api/3d/local-model/', ''))
const ext = getModelExtension(rawFileName)
const modelId = rawFileName.replace(/\.(?:glb|gltf)$/i, '')
const buffer = await readFile(localModelPath(modelId, ext))
response.writeHead(200, {
'Content-Type': ext === 'gltf' ? 'model/gltf+json' : 'model/gltf-binary',
'Cache-Control': 'private, max-age=3600',
})
response.end(buffer)
}
async function importLocalModel(request, url) {
const fileName = sanitizeFileName(url.searchParams.get('fileName') || 'local-model.glb')
const ext = getModelExtension(fileName)
const buffer = await readRawBody(request, MODEL_UPLOAD_LIMIT)
validateModelBuffer(buffer, ext)
const baseName = fileName.replace(/\.(?:glb|gltf)$/i, '') || 'local-model'
const modelId = `local-${Date.now()}-${baseName}`
await saveLocalModel(modelId, buffer, ext)
return {
provider: 'local',
taskId: sanitizeModelId(modelId),
status: 'success',
progress: 100,
modelUrl: localModelUrl(modelId, ext),
rawModelUrl: '',
fileName,
}
}
async function cacheRemoteModel(taskId, rawModelUrl) {
const ext = getModelExtension(rawModelUrl)
if (await hasLocalModel(taskId, ext)) return localModelUrl(taskId, ext)
await mkdir(LOCAL_MODEL_DIR, { recursive: true })
const targetPath = localModelPath(taskId, ext)
const tempPath = `${targetPath}.${Date.now()}.tmp`
try {
const remote = await fetchRemoteModel(rawModelUrl)
await pipeline(Readable.fromWeb(remote.body), createWriteStream(tempPath))
const buffer = await readFile(tempPath)
validateModelBuffer(buffer, ext)
await rename(tempPath, targetPath)
} catch (error) {
await rm(tempPath, { force: true }).catch(() => {})
throw error
}
return localModelUrl(taskId, ext)
}
async function fetchRemoteModel(rawUrl) {
const fetchOptions = shouldUseProxy(rawUrl) && OUTBOUND_PROXY_AGENT ? { dispatcher: OUTBOUND_PROXY_AGENT } : {}
const remote = await undiciFetch(rawUrl, fetchOptions)
if (remote.ok && remote.body) return remote
const retry = await undiciFetch(rawUrl, {
headers: { Authorization: `Bearer ${TRIPO_API_KEY}` },
...fetchOptions,
})
if (retry.ok && retry.body) return retry
throw Object.assign(new Error(`Model download failed with ${retry.status || remote.status}.`), { status: 502 })
}
function getModelExtension(value) {
const pathname = /^https?:\/\//i.test(String(value)) ? new URL(value).pathname : String(value)
const ext = path.extname(pathname).replace('.', '').toLowerCase()
if (ext === 'gltf') return 'gltf'
if (ext === 'glb') return 'glb'
throw Object.assign(new Error('Only GLB or self-contained GLTF models are supported.'), { status: 400 })
}
function validateModelBuffer(buffer, ext = 'glb') {
if (!Buffer.isBuffer(buffer) || buffer.length < 32) {
throw Object.assign(new Error('Model file is too small or invalid.'), { status: 400 })
}
if (ext === 'glb') {
if (buffer.subarray(0, 4).toString('ascii') !== 'glTF') {
throw Object.assign(new Error('GLB files must start with a glTF binary header.'), { status: 400 })
}
return
}
try {
JSON.parse(buffer.toString('utf8'))
} catch {
throw Object.assign(new Error('GLTF files must be valid JSON.'), { status: 400 })
}
}
function sanitizeModelId(value) {
return sanitizeFileName(String(value)).replace(/\.(?:glb|gltf)$/i, '').replace(/\s+/g, '-').slice(0, 96) || `model-${Date.now()}`
}
function sanitizeHunyuanRaw(raw) {
if (!raw || typeof raw !== 'object') return raw
return JSON.parse(JSON.stringify(raw, (key, value) => {
if (['model_base64', 'modelBase64', 'glb_base64', 'glbBase64'].includes(key)) return '[base64 omitted]'
return value
}))
}
function sanitizeTripoRaw(raw) {
if (!raw || typeof raw !== 'object') return raw
return JSON.parse(JSON.stringify(raw, (key, value) => {
if (['sts_ak', 'sts_sk', 'session_token'].includes(key)) return '[secret omitted]'
return value
}))
}
async function proxyModel(url, response) {
const rawUrl = url.searchParams.get('url')
if (!rawUrl || !isAllowedProxyModelUrl(rawUrl)) {
throw Object.assign(new Error('A valid HTTPS or localhost model URL is required.'), { status: 400 })
}
const fetchOptions = shouldUseProxy(rawUrl) && OUTBOUND_PROXY_AGENT ? { dispatcher: OUTBOUND_PROXY_AGENT } : {}
const remote = await undiciFetch(rawUrl, fetchOptions)
if (!remote.ok || !remote.body) {
const retry = await undiciFetch(rawUrl, {
headers: { Authorization: `Bearer ${TRIPO_API_KEY}` },
...fetchOptions,
})
if (!retry.ok || !retry.body) {
throw Object.assign(new Error(`Model download failed with ${retry.status || remote.status}.`), { status: 502 })
}
await streamRemoteModel(retry, response)
return
}
await streamRemoteModel(remote, response)
}
function isAllowedProxyModelUrl(rawUrl) {
try {
const parsed = new URL(rawUrl)
if (parsed.protocol === 'https:') return true
if (parsed.protocol !== 'http:') return false
return ['127.0.0.1', 'localhost', '::1'].includes(parsed.hostname)
} catch {
return false
}
}
async function streamRemoteModel(remote, response) {
response.writeHead(200, {
'Content-Type': remote.headers.get('content-type') || 'model/gltf-binary',
'Cache-Control': 'private, max-age=3600',
})
await pipeline(Readable.fromWeb(remote.body), response)
}
async function tripoRequest(path, options = {}) {
let response
try {
response = await undiciFetch(`${TRIPO_API_BASE}${path}`, {
...options,
...(OUTBOUND_PROXY_AGENT ? { dispatcher: OUTBOUND_PROXY_AGENT } : {}),
headers: {
Authorization: `Bearer ${TRIPO_API_KEY}`,
...(options.headers || {}),
},
})
} catch (error) {
const wrapped = new Error(`Tripo network request failed: ${error.message}`)
wrapped.detail = {
path,
cause: error.cause?.message || error.cause?.code || '',
proxy: Boolean(process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy),
}
throw wrapped
}
const text = await response.text()
let data = {}
try {
data = text ? JSON.parse(text) : {}
} catch {
data = { message: text || 'Non-JSON response from Tripo.' }
}
if (!response.ok || (typeof data.code === 'number' && data.code !== 0)) {
const error = new Error(data.message || data.error || `Tripo request failed with ${response.status}.`)
error.status = response.status || 502
error.detail = data
throw error
}
return data
}
function shouldUseProxy(rawUrl) {
try {
const parsed = new URL(rawUrl)
return !['127.0.0.1', 'localhost', '::1'].includes(parsed.hostname)
} catch {
return true
}
}
function findFirstValue(value, keys) {
if (!value || typeof value !== 'object') return ''
for (const key of keys) {
if (typeof value[key] === 'string' && value[key]) return value[key]
}
for (const child of Object.values(value)) {
if (Array.isArray(child)) {
for (const item of child) {
const found = findFirstValue(item, keys)
if (found) return found
}
} else if (child && typeof child === 'object') {
const found = findFirstValue(child, keys)
if (found) return found
}
}
return ''
}
function findModelUrl(value) {
const urls = []
collectUrls(value, urls)
const glb = urls.find((url) => /\.glb(?:[?#]|$)/i.test(url))
if (glb) return glb
return urls.find((url) => /\.(?:gltf|fbx|obj)(?:[?#]|$)/i.test(url)) || ''
}
function collectUrls(value, urls) {
if (!value) return
if (typeof value === 'string') {
if (/^https?:\/\//i.test(value)) urls.push(value)
return
}
if (Array.isArray(value)) {
value.forEach((item) => collectUrls(item, urls))
return
}
if (typeof value === 'object') {
Object.values(value).forEach((item) => collectUrls(item, urls))
}
}