mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(team): add integrations settings with turntable and gotenberg (#471)
* feat(team): add integrations settings with turntable and gotenberg * fix(upload): pass teamId to gotenberg availability check during upload preflight
This commit is contained in:
@@ -2,9 +2,12 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as os from 'os'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { GotenbergService } from './gotenberg'
|
||||
|
||||
describe('GotenbergService', () => {
|
||||
setupTestDbHooks()
|
||||
const originalEnv = process.env
|
||||
let tmpDir: string
|
||||
let testFilePath: string
|
||||
@@ -216,4 +219,148 @@ describe('GotenbergService', () => {
|
||||
expect(indexHtmlText).toContain('{{ toHTML "file.md" }}')
|
||||
})
|
||||
})
|
||||
|
||||
describe('team settings & fallback', () => {
|
||||
it('resolves config from team settings when env is not set', async () => {
|
||||
delete process.env.GOTENBERG_URL
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Gotenberg Team',
|
||||
settings: {
|
||||
gotenberg: {
|
||||
url: 'http://custom-gotenberg:4000',
|
||||
username: 'team-user',
|
||||
password: 'team-password',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const service = new GotenbergService()
|
||||
const config = await service.resolveConfig(team.id)
|
||||
|
||||
expect(config).toEqual({
|
||||
url: 'http://custom-gotenberg:4000',
|
||||
username: 'team-user',
|
||||
password: 'team-password',
|
||||
isEnv: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('prioritizes environment variables over team settings', async () => {
|
||||
process.env.GOTENBERG_URL = 'http://env-gotenberg:3000'
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Gotenberg Team',
|
||||
settings: {
|
||||
gotenberg: {
|
||||
url: 'http://custom-gotenberg:4000',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const service = new GotenbergService()
|
||||
const config = await service.resolveConfig(team.id)
|
||||
|
||||
expect(config.url).toBe('http://env-gotenberg:3000')
|
||||
expect(config.isEnv).toBe(true)
|
||||
})
|
||||
|
||||
it('getSettings returns masked settings response', async () => {
|
||||
delete process.env.GOTENBERG_URL
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Gotenberg Team',
|
||||
settings: {
|
||||
gotenberg: {
|
||||
url: 'http://custom-gotenberg:4000',
|
||||
username: 'team-user',
|
||||
password: 'team-password',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const service = new GotenbergService()
|
||||
const settings = await service.getSettings(team.id)
|
||||
|
||||
expect(settings).toEqual({
|
||||
url: 'http://custom-gotenberg:4000',
|
||||
username: 'team-user',
|
||||
hasPassword: true,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('updateSettings updates team settings and rejects edits when env is set', async () => {
|
||||
delete process.env.GOTENBERG_URL
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Gotenberg Team' },
|
||||
})
|
||||
|
||||
const service = new GotenbergService()
|
||||
const updated = await service.updateSettings(team.id, {
|
||||
url: 'http://new-gotenberg:3000',
|
||||
username: 'admin',
|
||||
password: 'secret-password',
|
||||
})
|
||||
|
||||
expect(updated.url).toBe('http://new-gotenberg:3000')
|
||||
expect(updated.username).toBe('admin')
|
||||
expect(updated.hasPassword).toBe(true)
|
||||
|
||||
// When env is set, reject update
|
||||
process.env.GOTENBERG_URL = 'http://env-gotenberg:3000'
|
||||
await expect(service.updateSettings(team.id, { url: 'http://another:3000' })).rejects.toThrow(
|
||||
'Gotenberg settings are configured via environment variables and cannot be edited',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('testConnection', () => {
|
||||
it('returns error when url is empty and no team settings exist', async () => {
|
||||
delete process.env.GOTENBERG_URL
|
||||
const service = new GotenbergService()
|
||||
const result = await service.testConnection({})
|
||||
expect(result.ok).toBe(false)
|
||||
expect(result.error).toBe('URL is required')
|
||||
})
|
||||
|
||||
it('successfully connects to /health and enriches with /version', async () => {
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {
|
||||
const urlStr = String(url)
|
||||
if (urlStr.endsWith('/health')) {
|
||||
return { ok: true, status: 200 } as Response
|
||||
}
|
||||
if (urlStr.endsWith('/version')) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ version: '8.3.0' }),
|
||||
} as Response
|
||||
}
|
||||
return { ok: false, status: 404 } as Response
|
||||
})
|
||||
|
||||
const service = new GotenbergService()
|
||||
const result = await service.testConnection({
|
||||
url: 'http://gotenberg.local:3000',
|
||||
username: 'test-user',
|
||||
password: 'test-pass',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(result.version).toBe('8.3.0')
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
'http://gotenberg.local:3000/health',
|
||||
expect.objectContaining({
|
||||
method: 'GET',
|
||||
headers: expect.objectContaining({
|
||||
Authorization: expect.stringMatching(/^Basic /),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,40 +1,135 @@
|
||||
import * as fs from 'fs'
|
||||
import type { GotenbergSettingsResponse, UpdateGotenbergSettingsRequest } from '@shumai/dtos'
|
||||
import {
|
||||
IntegrationDefinition,
|
||||
resolveIntegrationConfig,
|
||||
getIntegrationSettings,
|
||||
updateIntegrationSettings,
|
||||
resolveTestConnectionConfig,
|
||||
getIntegrationBasicAuthHeader,
|
||||
ResolvedIntegrationConfig,
|
||||
} from '@shumai/core/src/integrations/helper'
|
||||
|
||||
export const GOTENBERG_INTEGRATION_DEF: IntegrationDefinition<'gotenberg'> = {
|
||||
name: 'Gotenberg',
|
||||
settingsKey: 'gotenberg',
|
||||
envKeys: {
|
||||
url: ['GOTENBERG_URL'],
|
||||
username: ['GOTENBERG_BASIC_AUTH_USERNAME'],
|
||||
password: ['GOTENBERG_BASIC_AUTH_PASSWORD'],
|
||||
},
|
||||
}
|
||||
|
||||
export interface GotenbergConvertOptions {
|
||||
landscape?: boolean
|
||||
teamId?: string
|
||||
}
|
||||
|
||||
export class GotenbergService {
|
||||
private getUrl(): string | undefined {
|
||||
const url = process.env.GOTENBERG_URL?.trim()
|
||||
return url ? url.replace(/\/+$/, '') : undefined
|
||||
async resolveConfig(teamId?: string): Promise<ResolvedIntegrationConfig> {
|
||||
return resolveIntegrationConfig(GOTENBERG_INTEGRATION_DEF, teamId)
|
||||
}
|
||||
|
||||
private getAuthHeader(): string | undefined {
|
||||
const username = process.env.GOTENBERG_BASIC_AUTH_USERNAME
|
||||
const password = process.env.GOTENBERG_BASIC_AUTH_PASSWORD
|
||||
private getAuthHeader(config: { username?: string; password?: string }): string | undefined {
|
||||
return getIntegrationBasicAuthHeader(config)
|
||||
}
|
||||
|
||||
if (username && password) {
|
||||
const credentials = Buffer.from(`${username}:${password}`).toString('base64')
|
||||
return `Basic ${credentials}`
|
||||
async getSettings(teamId: string): Promise<GotenbergSettingsResponse> {
|
||||
return getIntegrationSettings(GOTENBERG_INTEGRATION_DEF, teamId)
|
||||
}
|
||||
|
||||
async updateSettings(
|
||||
teamId: string,
|
||||
req: UpdateGotenbergSettingsRequest,
|
||||
): Promise<GotenbergSettingsResponse> {
|
||||
return updateIntegrationSettings(GOTENBERG_INTEGRATION_DEF, teamId, req)
|
||||
}
|
||||
|
||||
async testConnection(
|
||||
config?: UpdateGotenbergSettingsRequest,
|
||||
teamId?: string,
|
||||
): Promise<{ ok: boolean; version?: string; error?: string }> {
|
||||
const target = await resolveTestConnectionConfig(GOTENBERG_INTEGRATION_DEF, config, teamId)
|
||||
|
||||
if (!target.resolvedUrl) {
|
||||
return { ok: false, error: 'URL is required' }
|
||||
}
|
||||
const cleanUrl = target.resolvedUrl.replace(/\/+$/, '')
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader({
|
||||
username: target.resolvedUsername,
|
||||
password: target.resolvedPassword,
|
||||
})
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${cleanUrl}/health`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text().catch(() => '')
|
||||
return {
|
||||
ok: false,
|
||||
error: `Health check returned status ${response.status}: ${errText || response.statusText}`,
|
||||
}
|
||||
}
|
||||
|
||||
// Optionally try /version to obtain version string
|
||||
let version: string | undefined
|
||||
try {
|
||||
const versionRes = await fetch(`${cleanUrl}/version`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(2000),
|
||||
})
|
||||
if (versionRes.ok) {
|
||||
const vData = (await versionRes.json().catch(() => null)) as
|
||||
| { version?: string }
|
||||
| string
|
||||
| null
|
||||
if (vData && typeof vData === 'object' && 'version' in vData) {
|
||||
version = String(vData.version)
|
||||
} else if (typeof vData === 'string') {
|
||||
version = vData
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Version endpoint is optional in some Gotenberg versions
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
version,
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
return {
|
||||
ok: false,
|
||||
error: msg,
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
const baseUrl = this.getUrl()
|
||||
if (!baseUrl) {
|
||||
async isAvailable(teamId?: string): Promise<boolean> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader()
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${baseUrl}/health`, {
|
||||
const response = await fetch(`${config.url}/health`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
signal: AbortSignal.timeout(3000),
|
||||
@@ -50,9 +145,11 @@ export class GotenbergService {
|
||||
filePath: string,
|
||||
filename: string,
|
||||
options: GotenbergConvertOptions = {},
|
||||
teamId?: string,
|
||||
): Promise<Buffer> {
|
||||
const baseUrl = this.getUrl()
|
||||
if (!baseUrl) {
|
||||
const effectiveTeamId = teamId ?? options.teamId
|
||||
const config = await this.resolveConfig(effectiveTeamId)
|
||||
if (!config.url) {
|
||||
throw new Error('Gotenberg URL is not configured.')
|
||||
}
|
||||
|
||||
@@ -65,12 +162,12 @@ export class GotenbergService {
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader()
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${baseUrl}/forms/libreoffice/convert`, {
|
||||
const response = await fetch(`${config.url}/forms/libreoffice/convert`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
@@ -88,9 +185,9 @@ export class GotenbergService {
|
||||
return Buffer.from(arrayBuffer)
|
||||
}
|
||||
|
||||
async convertHtmlToPdf(filePath: string, filename: string): Promise<Buffer> {
|
||||
const baseUrl = this.getUrl()
|
||||
if (!baseUrl) {
|
||||
async convertHtmlToPdf(filePath: string, filename: string, teamId?: string): Promise<Buffer> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
throw new Error('Gotenberg URL is not configured.')
|
||||
}
|
||||
|
||||
@@ -103,12 +200,12 @@ export class GotenbergService {
|
||||
formData.append('files', new Blob([fileBytes]), targetFilename)
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader()
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${baseUrl}/forms/chromium/convert/html`, {
|
||||
const response = await fetch(`${config.url}/forms/chromium/convert/html`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
@@ -126,9 +223,9 @@ export class GotenbergService {
|
||||
return Buffer.from(arrayBuffer)
|
||||
}
|
||||
|
||||
async convertMarkdownToPdf(filePath: string, filename: string): Promise<Buffer> {
|
||||
const baseUrl = this.getUrl()
|
||||
if (!baseUrl) {
|
||||
async convertMarkdownToPdf(filePath: string, filename: string, teamId?: string): Promise<Buffer> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
if (!config.url) {
|
||||
throw new Error('Gotenberg URL is not configured.')
|
||||
}
|
||||
|
||||
@@ -151,12 +248,12 @@ export class GotenbergService {
|
||||
formData.append('files', new Blob([fileBytes]), mdFilename)
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const authHeader = this.getAuthHeader()
|
||||
const authHeader = this.getAuthHeader(config)
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${baseUrl}/forms/chromium/convert/markdown`, {
|
||||
const response = await fetch(`${config.url}/forms/chromium/convert/markdown`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData,
|
||||
|
||||
@@ -32,3 +32,4 @@ export * from './media-generation/media-generation'
|
||||
export * from './sandbox'
|
||||
export * from './asset/comments-export'
|
||||
export * from './turntable/turntable'
|
||||
export * from './integrations/helper'
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import {
|
||||
IntegrationDefinition,
|
||||
resolveIntegrationConfig,
|
||||
getIntegrationSettings,
|
||||
updateIntegrationSettings,
|
||||
resolveTestConnectionConfig,
|
||||
getIntegrationBasicAuthHeader,
|
||||
} from './helper'
|
||||
|
||||
const TEST_INTEGRATION_DEF: IntegrationDefinition<'turntable'> = {
|
||||
name: 'TestIntegration',
|
||||
settingsKey: 'turntable',
|
||||
envKeys: {
|
||||
url: ['TEST_INTEGRATION_URL', 'FALLBACK_INTEGRATION_URL'],
|
||||
username: ['TEST_INTEGRATION_USERNAME'],
|
||||
password: ['TEST_INTEGRATION_PASSWORD'],
|
||||
},
|
||||
}
|
||||
|
||||
describe('Integration Config Helper', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const originalEnv = process.env
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...originalEnv }
|
||||
delete process.env.TEST_INTEGRATION_URL
|
||||
delete process.env.FALLBACK_INTEGRATION_URL
|
||||
delete process.env.TEST_INTEGRATION_USERNAME
|
||||
delete process.env.TEST_INTEGRATION_PASSWORD
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv
|
||||
})
|
||||
|
||||
describe('resolveIntegrationConfig', () => {
|
||||
it('prioritizes environment variables over database settings', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
turntable: {
|
||||
url: 'http://db-server:1234',
|
||||
username: 'db-user',
|
||||
password: 'db-password',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
process.env.TEST_INTEGRATION_URL = 'http://env-server:5678/'
|
||||
process.env.TEST_INTEGRATION_USERNAME = 'env-user'
|
||||
process.env.TEST_INTEGRATION_PASSWORD = 'env-pass'
|
||||
|
||||
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
|
||||
expect(config).toEqual({
|
||||
url: 'http://env-server:5678',
|
||||
username: 'env-user',
|
||||
password: 'env-pass',
|
||||
isEnv: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to second env key if first is missing', async () => {
|
||||
process.env.FALLBACK_INTEGRATION_URL = 'http://fallback-server:8080'
|
||||
|
||||
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF)
|
||||
expect(config.url).toBe('http://fallback-server:8080')
|
||||
expect(config.isEnv).toBe(true)
|
||||
})
|
||||
|
||||
it('reads from team settings when environment variables are not set', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
turntable: {
|
||||
url: 'http://db-server:1234/',
|
||||
username: 'db-user',
|
||||
password: 'db-password',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
|
||||
expect(config).toEqual({
|
||||
url: 'http://db-server:1234',
|
||||
username: 'db-user',
|
||||
password: 'db-password',
|
||||
isEnv: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns isEnv: false and undefined fields when neither env nor DB are set', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Empty Team' },
|
||||
})
|
||||
|
||||
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
|
||||
expect(config).toEqual({
|
||||
isEnv: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getIntegrationSettings', () => {
|
||||
it('returns safe response masking password', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
turntable: {
|
||||
url: 'http://db-server:1234',
|
||||
username: 'db-user',
|
||||
password: 'db-password',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const res = await getIntegrationSettings(TEST_INTEGRATION_DEF, team.id)
|
||||
expect(res).toEqual({
|
||||
url: 'http://db-server:1234',
|
||||
username: 'db-user',
|
||||
hasPassword: true,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('updateIntegrationSettings', () => {
|
||||
it('throws error when environment variable is configured', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Test Team' },
|
||||
})
|
||||
|
||||
process.env.TEST_INTEGRATION_URL = 'http://env-server:5678'
|
||||
|
||||
await expect(
|
||||
updateIntegrationSettings(TEST_INTEGRATION_DEF, team.id, {
|
||||
url: 'http://new-url:1234',
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'TestIntegration settings are configured via environment variables and cannot be edited',
|
||||
)
|
||||
})
|
||||
|
||||
it('updates settings and preserves existing password when not supplied', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
turntable: {
|
||||
url: 'http://original:1234',
|
||||
username: 'original-user',
|
||||
password: 'secret-password',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const res = await updateIntegrationSettings(TEST_INTEGRATION_DEF, team.id, {
|
||||
url: 'http://updated:5678/',
|
||||
username: 'new-user',
|
||||
})
|
||||
|
||||
expect(res).toEqual({
|
||||
url: 'http://updated:5678',
|
||||
username: 'new-user',
|
||||
hasPassword: true,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
|
||||
const config = await resolveIntegrationConfig(TEST_INTEGRATION_DEF, team.id)
|
||||
expect(config.password).toBe('secret-password')
|
||||
})
|
||||
|
||||
it('clears settings in database when URL is empty or whitespace', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
turntable: {
|
||||
url: 'http://to-be-cleared:1234',
|
||||
username: 'user',
|
||||
password: 'pwd',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const res = await updateIntegrationSettings(TEST_INTEGRATION_DEF, team.id, {
|
||||
url: ' ',
|
||||
})
|
||||
|
||||
expect(res).toEqual({
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
hasPassword: false,
|
||||
isEnvConfigured: false,
|
||||
})
|
||||
|
||||
const updatedTeam = await prisma.team.findUnique({
|
||||
where: { id: team.id },
|
||||
})
|
||||
// Check that turntable is removed from team settings
|
||||
expect((updatedTeam?.settings as Record<string, unknown>)?.turntable).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveTestConnectionConfig', () => {
|
||||
it('uses provided credentials directly when supplied', async () => {
|
||||
const target = await resolveTestConnectionConfig(TEST_INTEGRATION_DEF, {
|
||||
url: 'http://direct:1234',
|
||||
username: 'direct-user',
|
||||
password: 'direct-password',
|
||||
})
|
||||
|
||||
expect(target).toEqual({
|
||||
resolvedUrl: 'http://direct:1234',
|
||||
resolvedUsername: 'direct-user',
|
||||
resolvedPassword: 'direct-password',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to saved database settings when testing with partial inputs', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
turntable: {
|
||||
url: 'http://db:1234',
|
||||
username: 'db-user',
|
||||
password: 'db-password',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const target = await resolveTestConnectionConfig(
|
||||
TEST_INTEGRATION_DEF,
|
||||
{ url: 'http://new-url:9999' },
|
||||
team.id,
|
||||
)
|
||||
|
||||
expect(target).toEqual({
|
||||
resolvedUrl: 'http://new-url:9999',
|
||||
resolvedUsername: 'db-user',
|
||||
resolvedPassword: 'db-password',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getIntegrationBasicAuthHeader', () => {
|
||||
it('generates base64 basic auth header when username and password are provided', () => {
|
||||
const header = getIntegrationBasicAuthHeader({ username: 'admin', password: 'secret' })
|
||||
expect(header).toBe(`Basic ${Buffer.from('admin:secret').toString('base64')}`)
|
||||
})
|
||||
|
||||
it('returns undefined when username or password is missing', () => {
|
||||
expect(getIntegrationBasicAuthHeader({ username: 'admin' })).toBeUndefined()
|
||||
expect(getIntegrationBasicAuthHeader({ password: 'secret' })).toBeUndefined()
|
||||
expect(getIntegrationBasicAuthHeader({})).toBeUndefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,188 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export interface IntegrationEnvKeys {
|
||||
url: string[]
|
||||
username?: string[]
|
||||
password?: string[]
|
||||
}
|
||||
|
||||
export interface IntegrationDefinition<TKey extends keyof PrismaJson.Settings> {
|
||||
name: string
|
||||
settingsKey: TKey
|
||||
envKeys: IntegrationEnvKeys
|
||||
}
|
||||
|
||||
export interface ResolvedIntegrationConfig {
|
||||
url?: string
|
||||
username?: string
|
||||
password?: string
|
||||
isEnv: boolean
|
||||
}
|
||||
|
||||
export interface IntegrationSettingsResponse {
|
||||
url?: string
|
||||
username?: string
|
||||
hasPassword: boolean
|
||||
isEnvConfigured: boolean
|
||||
}
|
||||
|
||||
export interface UpdateIntegrationSettingsRequest {
|
||||
url?: string
|
||||
username?: string
|
||||
password?: string
|
||||
}
|
||||
|
||||
function getFirstEnvValue(keys?: string[]): string | undefined {
|
||||
if (!keys) return undefined
|
||||
for (const key of keys) {
|
||||
const val = process.env[key]?.trim()
|
||||
if (val) return val
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export async function resolveIntegrationConfig<TKey extends keyof PrismaJson.Settings>(
|
||||
def: IntegrationDefinition<TKey>,
|
||||
teamId?: string,
|
||||
): Promise<ResolvedIntegrationConfig> {
|
||||
const envUrl = getFirstEnvValue(def.envKeys.url)
|
||||
const envUsername = getFirstEnvValue(def.envKeys.username)
|
||||
const envPassword = getFirstEnvValue(def.envKeys.password)
|
||||
|
||||
if (envUrl) {
|
||||
return {
|
||||
url: envUrl.replace(/\/+$/, ''),
|
||||
username: envUsername || undefined,
|
||||
password: envPassword || undefined,
|
||||
isEnv: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (teamId) {
|
||||
try {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
const teamSettings = team?.settings as PrismaJson.Settings | null
|
||||
const serviceSettings = teamSettings?.[def.settingsKey] as
|
||||
| { url?: string; username?: string; password?: string }
|
||||
| undefined
|
||||
|
||||
if (serviceSettings?.url?.trim()) {
|
||||
return {
|
||||
url: serviceSettings.url.trim().replace(/\/+$/, ''),
|
||||
username: serviceSettings.username?.trim() || undefined,
|
||||
password: serviceSettings.password?.trim() || undefined,
|
||||
isEnv: false,
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err, teamId }, `Failed to load team ${def.name} settings`)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isEnv: false,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getIntegrationSettings<TKey extends keyof PrismaJson.Settings>(
|
||||
def: IntegrationDefinition<TKey>,
|
||||
teamId: string,
|
||||
): Promise<IntegrationSettingsResponse> {
|
||||
const config = await resolveIntegrationConfig(def, teamId)
|
||||
return {
|
||||
url: config.url,
|
||||
username: config.username,
|
||||
hasPassword: Boolean(config.password),
|
||||
isEnvConfigured: config.isEnv,
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateIntegrationSettings<TKey extends keyof PrismaJson.Settings>(
|
||||
def: IntegrationDefinition<TKey>,
|
||||
teamId: string,
|
||||
req: UpdateIntegrationSettingsRequest,
|
||||
): Promise<IntegrationSettingsResponse> {
|
||||
const currentConfig = await resolveIntegrationConfig(def, teamId)
|
||||
if (currentConfig.isEnv) {
|
||||
throw new Error(
|
||||
`${def.name} settings are configured via environment variables and cannot be edited`,
|
||||
)
|
||||
}
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
const settings = { ...((team?.settings || {}) as PrismaJson.Settings) }
|
||||
const prevSettings = (settings[def.settingsKey] || {}) as {
|
||||
url?: string
|
||||
username?: string
|
||||
password?: string
|
||||
}
|
||||
|
||||
const trimmedUrl = req.url?.trim()
|
||||
if (!trimmedUrl) {
|
||||
// If URL is empty/unset, clear the integration settings
|
||||
delete settings[def.settingsKey]
|
||||
} else {
|
||||
const updatedServiceSettings: { url: string; username?: string; password?: string } = {
|
||||
url: trimmedUrl.replace(/\/+$/, ''),
|
||||
username:
|
||||
req.username !== undefined ? req.username.trim() || undefined : prevSettings.username,
|
||||
password: req.password !== undefined ? req.password : prevSettings.password,
|
||||
}
|
||||
settings[def.settingsKey] = updatedServiceSettings as unknown as PrismaJson.Settings[TKey]
|
||||
}
|
||||
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: { settings },
|
||||
})
|
||||
|
||||
return getIntegrationSettings(def, teamId)
|
||||
}
|
||||
|
||||
export async function resolveTestConnectionConfig<TKey extends keyof PrismaJson.Settings>(
|
||||
def: IntegrationDefinition<TKey>,
|
||||
config?: UpdateIntegrationSettingsRequest,
|
||||
teamId?: string,
|
||||
): Promise<{ resolvedUrl?: string; resolvedUsername?: string; resolvedPassword?: string }> {
|
||||
let resolvedUrl = config?.url?.trim()
|
||||
let resolvedUsername = config?.username?.trim()
|
||||
let resolvedPassword = config?.password
|
||||
|
||||
if (teamId && (!resolvedUrl || resolvedPassword === undefined)) {
|
||||
const savedConfig = await resolveIntegrationConfig(def, teamId)
|
||||
if (!resolvedUrl) {
|
||||
resolvedUrl = savedConfig.url
|
||||
}
|
||||
if (!resolvedUsername && savedConfig.username) {
|
||||
resolvedUsername = savedConfig.username
|
||||
}
|
||||
if (resolvedPassword === undefined) {
|
||||
resolvedPassword = savedConfig.password
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
resolvedUrl,
|
||||
resolvedUsername,
|
||||
resolvedPassword,
|
||||
}
|
||||
}
|
||||
|
||||
export function getIntegrationBasicAuthHeader(config: {
|
||||
username?: string
|
||||
password?: string
|
||||
}): string | undefined {
|
||||
if (config.username && config.password) {
|
||||
const credentials = Buffer.from(`${config.username}:${config.password}`).toString('base64')
|
||||
return `Basic ${credentials}`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@@ -381,6 +381,12 @@ describe('TeamService', () => {
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
gotenberg: {
|
||||
hasPassword: false,
|
||||
isEnvConfigured: false,
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
|
||||
@@ -404,6 +410,12 @@ describe('TeamService', () => {
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
gotenberg: {
|
||||
hasPassword: false,
|
||||
isEnvConfigured: false,
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: false },
|
||||
})
|
||||
|
||||
@@ -436,6 +448,12 @@ describe('TeamService', () => {
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
gotenberg: {
|
||||
hasPassword: false,
|
||||
isEnvConfigured: false,
|
||||
url: undefined,
|
||||
username: undefined,
|
||||
},
|
||||
appearance: { hideAgent: true },
|
||||
semanticSearchEnabled: false,
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import { HTTPException } from 'hono/http-exception'
|
||||
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
|
||||
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import {
|
||||
ServiceCreateTeamRequest,
|
||||
ServiceGetUserTeamsRequest,
|
||||
@@ -345,6 +346,7 @@ export class TeamService {
|
||||
}
|
||||
|
||||
settings.turntable = await turntableService.getSettings(teamId)
|
||||
settings.gotenberg = await gotenbergService.getSettings(teamId)
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
import * as fs from 'fs'
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { TurntableSettingsResponse, UpdateTurntableSettingsRequest } from '@shumai/dtos'
|
||||
import { logger } from '../logger'
|
||||
import {
|
||||
IntegrationDefinition,
|
||||
resolveIntegrationConfig,
|
||||
getIntegrationSettings,
|
||||
updateIntegrationSettings,
|
||||
resolveTestConnectionConfig,
|
||||
getIntegrationBasicAuthHeader,
|
||||
} from '@shumai/core/src/integrations/helper'
|
||||
|
||||
export const TURNTABLE_INTEGRATION_DEF: IntegrationDefinition<'turntable'> = {
|
||||
name: 'Turntable',
|
||||
settingsKey: 'turntable',
|
||||
envKeys: {
|
||||
url: ['TURNTABLE_RENDERER_URL'],
|
||||
username: ['TURNTABLE_RENDERER_BASIC_AUTH_USERNAME', 'TURNTABLE_RENDERER_USERNAME'],
|
||||
password: ['TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD', 'TURNTABLE_RENDERER_PASSWORD'],
|
||||
},
|
||||
}
|
||||
|
||||
export interface TurntableConfig {
|
||||
url?: string
|
||||
@@ -67,55 +83,11 @@ export interface TurntableTaskResponse {
|
||||
|
||||
export class TurntableService {
|
||||
async resolveConfig(teamId?: string): Promise<TurntableConfig> {
|
||||
const envUrl = process.env.TURNTABLE_RENDERER_URL?.trim()
|
||||
const envUsername =
|
||||
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME?.trim() ||
|
||||
process.env.TURNTABLE_RENDERER_USERNAME?.trim()
|
||||
const envPassword =
|
||||
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD?.trim() ||
|
||||
process.env.TURNTABLE_RENDERER_PASSWORD?.trim()
|
||||
|
||||
if (envUrl) {
|
||||
return {
|
||||
url: envUrl.replace(/\/+$/, ''),
|
||||
username: envUsername || undefined,
|
||||
password: envPassword || undefined,
|
||||
isEnv: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (teamId) {
|
||||
try {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
const teamSettings = team?.settings as PrismaJson.Settings | null
|
||||
const turntable = teamSettings?.turntable
|
||||
if (turntable?.url?.trim()) {
|
||||
return {
|
||||
url: turntable.url.trim().replace(/\/+$/, ''),
|
||||
username: turntable.username?.trim() || undefined,
|
||||
password: turntable.password?.trim() || undefined,
|
||||
isEnv: false,
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err, teamId }, 'Failed to load team turntable settings')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isEnv: false,
|
||||
}
|
||||
return resolveIntegrationConfig(TURNTABLE_INTEGRATION_DEF, teamId)
|
||||
}
|
||||
|
||||
private getAuthHeader(config: TurntableConfig): string | undefined {
|
||||
if (config.username && config.password) {
|
||||
const credentials = Buffer.from(`${config.username}:${config.password}`).toString('base64')
|
||||
return `Basic ${credentials}`
|
||||
}
|
||||
return undefined
|
||||
return getIntegrationBasicAuthHeader(config)
|
||||
}
|
||||
|
||||
async isAvailable(teamId?: string): Promise<boolean> {
|
||||
@@ -144,45 +116,14 @@ export class TurntableService {
|
||||
}
|
||||
|
||||
async getSettings(teamId: string): Promise<TurntableSettingsResponse> {
|
||||
const config = await this.resolveConfig(teamId)
|
||||
return {
|
||||
url: config.url,
|
||||
username: config.username,
|
||||
hasPassword: Boolean(config.password),
|
||||
isEnvConfigured: config.isEnv,
|
||||
}
|
||||
return getIntegrationSettings(TURNTABLE_INTEGRATION_DEF, teamId)
|
||||
}
|
||||
|
||||
async updateSettings(
|
||||
teamId: string,
|
||||
req: UpdateTurntableSettingsRequest,
|
||||
): Promise<TurntableSettingsResponse> {
|
||||
const currentConfig = await this.resolveConfig(teamId)
|
||||
if (currentConfig.isEnv) {
|
||||
throw new Error(
|
||||
'Turntable settings are configured via environment variables and cannot be edited',
|
||||
)
|
||||
}
|
||||
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
const settings = (team?.settings || {}) as PrismaJson.Settings
|
||||
const prevTurntable = settings.turntable || {}
|
||||
|
||||
settings.turntable = {
|
||||
url: req.url !== undefined ? req.url : prevTurntable.url,
|
||||
username: req.username !== undefined ? req.username : prevTurntable.username,
|
||||
password: req.password !== undefined ? req.password : prevTurntable.password,
|
||||
}
|
||||
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: { settings },
|
||||
})
|
||||
|
||||
return this.getSettings(teamId)
|
||||
return updateIntegrationSettings(TURNTABLE_INTEGRATION_DEF, teamId, req)
|
||||
}
|
||||
|
||||
async testConnection(
|
||||
@@ -193,35 +134,21 @@ export class TurntableService {
|
||||
},
|
||||
teamId?: string,
|
||||
): Promise<{ ok: boolean; version?: string; blender?: string; error?: string }> {
|
||||
let resolvedUrl = config?.url?.trim()
|
||||
let resolvedUsername = config?.username?.trim()
|
||||
let resolvedPassword = config?.password
|
||||
const target = await resolveTestConnectionConfig(TURNTABLE_INTEGRATION_DEF, config, teamId)
|
||||
|
||||
if (teamId && (!resolvedUrl || resolvedPassword === undefined)) {
|
||||
const savedConfig = await this.resolveConfig(teamId)
|
||||
if (!resolvedUrl) {
|
||||
resolvedUrl = savedConfig.url
|
||||
}
|
||||
if (!resolvedUsername && savedConfig.username) {
|
||||
resolvedUsername = savedConfig.username
|
||||
}
|
||||
if (resolvedPassword === undefined) {
|
||||
resolvedPassword = savedConfig.password
|
||||
}
|
||||
}
|
||||
|
||||
if (!resolvedUrl) {
|
||||
if (!target.resolvedUrl) {
|
||||
return { ok: false, error: 'URL is required' }
|
||||
}
|
||||
const cleanUrl = resolvedUrl.replace(/\/+$/, '')
|
||||
const cleanUrl = target.resolvedUrl.replace(/\/+$/, '')
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {}
|
||||
if (resolvedUsername && resolvedPassword) {
|
||||
const credentials = Buffer.from(`${resolvedUsername}:${resolvedPassword}`).toString(
|
||||
'base64',
|
||||
)
|
||||
headers['Authorization'] = `Basic ${credentials}`
|
||||
const authHeader = getIntegrationBasicAuthHeader({
|
||||
username: target.resolvedUsername,
|
||||
password: target.resolvedPassword,
|
||||
})
|
||||
if (authHeader) {
|
||||
headers['Authorization'] = authHeader
|
||||
}
|
||||
|
||||
const response = await fetch(`${cleanUrl}/version`, {
|
||||
|
||||
@@ -451,6 +451,93 @@ describe('UploadService', () => {
|
||||
expect(workflowTask).toBeNull()
|
||||
})
|
||||
|
||||
it('should create transcode_pdf for office documents when Gotenberg is configured in team settings without global env', async () => {
|
||||
vi.restoreAllMocks()
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes('/health')) {
|
||||
return new Response(JSON.stringify({ status: 'up' }), { status: 200 })
|
||||
}
|
||||
return new Response('Not Found', { status: 404 })
|
||||
})
|
||||
const originalEnv = process.env.GOTENBERG_URL
|
||||
delete process.env.GOTENBERG_URL
|
||||
|
||||
try {
|
||||
await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
settings: {
|
||||
gotenberg: {
|
||||
url: 'http://gotenberg.local:3000',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.task.create({
|
||||
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'report.docx',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key-doc-team-settings' },
|
||||
create: { key: 'test-key-doc-team-settings' },
|
||||
},
|
||||
},
|
||||
mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
},
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
|
||||
|
||||
const workflowTask = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
|
||||
})
|
||||
expect(workflowTask).not.toBeNull()
|
||||
expect(workflowTask?.status).toBe(TaskStatus.pending)
|
||||
|
||||
// Test HTML document as well
|
||||
const htmlTask = await prisma.task.create({
|
||||
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
|
||||
})
|
||||
const htmlAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'index.html',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
status: AssetStatus.uploading,
|
||||
storageKey: {
|
||||
connectOrCreate: {
|
||||
where: { key: 'test-key-html-team-settings' },
|
||||
create: { key: 'test-key-html-team-settings' },
|
||||
},
|
||||
},
|
||||
mediaType: 'text/html',
|
||||
},
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(userId, htmlTask.id, { fileId: htmlAsset.id })
|
||||
|
||||
const htmlWorkflowTask = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: htmlAsset.id, type: WorkflowTaskType.transcode_pdf },
|
||||
})
|
||||
expect(htmlWorkflowTask).not.toBeNull()
|
||||
expect(htmlWorkflowTask?.status).toBe(TaskStatus.pending)
|
||||
} finally {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env.GOTENBERG_URL = originalEnv
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('should confirm file upload and create transcode_3d for 3D model when turntable is available', async () => {
|
||||
vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(true)
|
||||
const task = await prisma.task.create({
|
||||
|
||||
@@ -363,7 +363,7 @@ export class UploadService {
|
||||
const isHtml = isHtmlDocument(asset.mediaType, asset.name)
|
||||
|
||||
if (isOffice || isHtml) {
|
||||
const gotenbergAvailable = await gotenbergService.isAvailable()
|
||||
const gotenbergAvailable = await gotenbergService.isAvailable(team.id)
|
||||
if (!gotenbergAvailable) {
|
||||
await tx.asset.update({
|
||||
where: { id: asset.id },
|
||||
|
||||
Reference in New Issue
Block a user