Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,13 @@ const handleRequest = async (req, res) => {
}

res.setHeader('Content-Type', 'application/json')
res.setHeader('Access-Control-Allow-Origin', '*')

const origin = req.headers.origin || ''
const allowedOrigin = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin) ? origin : ''
res.setHeader('Access-Control-Allow-Origin', allowedOrigin)
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
res.setHeader('Vary', 'Origin')

if (method === HTTP_METHODS.OPTIONS) {
res.statusCode = 204
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
'use strict'

const { InferenceArgsSchema } = require('../validation')
const { spawn } = require('bare-subprocess')
const logger = require('../utils/logger')
const fs = require('bare-fs')
const { Readable } = require('bare-stream')
const process = require('bare-process')
const path = require('bare-path')

const ALLOWED_LIBS = [
'@qvac/transcription-parakeet'
]

const loadedModels = new Map()

const ALLOWED_AUDIO_DIRS = [
path.resolve('.'),
path.resolve('./models'),
path.resolve('./examples')
]

const validateFilePath = (filePath) => {
const resolved = path.resolve(filePath)
if (!fs.existsSync(resolved)) {
throw new Error('File not found')
}
const isAllowed = ALLOWED_AUDIO_DIRS.some(dir => resolved.startsWith(dir + path.sep) || resolved === dir)
if (!isAllowed) {
throw new Error('File path is outside allowed directories')
}
return resolved
}

const getPackageVersion = (lib) => {
try {
const packagePath = require.resolve(`${lib}/package`)
Expand All @@ -21,43 +42,6 @@ const getPackageVersion = (lib) => {
}
}

const ensurePackage = async (lib, requestedVersion) => {
const installed = getPackageVersion(lib)

// If package is already installed, use it (skip version check for local installs)
if (installed) {
if (!requestedVersion || installed === requestedVersion) {
logger.info(`Using installed ${lib}@${installed}`)
return installed
}
// Version mismatch but package is installed - use installed version with warning
logger.warn(`Requested ${lib}@${requestedVersion} but ${installed} is installed. Using installed version.`)
return installed
}

// Package not installed - try to install from npm
const versionSpec = requestedVersion ? `@${requestedVersion}` : ''
logger.info(`Installing ${lib}${versionSpec}...`)
await new Promise((resolve, reject) => {
const npm = spawn('npm', ['install', `${lib}${versionSpec}`], { stdio: 'inherit' })
npm
.on('exit', code => code === 0 ? resolve() : reject(new Error(`npm install ${lib}${versionSpec} failed (${code})`)))
.on('error', reject)
})

// Try to get version after install, but don't fail if we can't verify
// (Bare runtime has different module resolution than Node.js)
const newVersion = getPackageVersion(lib)
if (newVersion) {
logger.info(`Installed ${lib}@${newVersion}`)
return newVersion
}

// Package installed but version couldn't be verified - return 'unknown'
logger.warn(`Installed ${lib} but couldn't verify version (Bare runtime). Proceeding anyway.`)
return 'unknown'
}

class FakeLoader {
async start () {}
async stop () {}
Expand Down Expand Up @@ -118,9 +102,13 @@ const runAddon = async (payload) => {
const { inputs, parakeet, config } =
InferenceArgsSchema.parse(payload)

const { lib: parakeetLib, version: parakeetVerReq } = parakeet
const { lib: parakeetLib } = parakeet

if (!ALLOWED_LIBS.includes(parakeetLib)) {
throw new Error('Unsupported library: ' + parakeetLib + '. Allowed: ' + ALLOWED_LIBS.join(', '))
}

const parakeetVersion = await ensurePackage(parakeetLib, parakeetVerReq)
const parakeetVersion = getPackageVersion(parakeetLib) || 'unknown'
logger.info(`Loading addon: ${parakeetLib}`)
const TranscriptionParakeet = require(parakeetLib)
logger.info('Addon loaded successfully')
Expand All @@ -144,6 +132,7 @@ const runAddon = async (payload) => {
if (!config.path) {
throw new Error('Model path is required in config')
}
validateFilePath(config.path)

const constructorArgs = {
loader: new FakeLoader(),
Expand Down Expand Up @@ -191,7 +180,8 @@ const runAddon = async (payload) => {
const runStart = process.hrtime()

for (const audioFilePath of inputs) {
const audioBuffer = fs.readFileSync(audioFilePath)
const resolvedAudioPath = validateFilePath(audioFilePath)
const audioBuffer = fs.readFileSync(resolvedAudioPath)
const segments = []

let audioStream
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,30 @@

const { ERRORS } = require('./constants')
const ApiError = require('./ApiError')
const { Buffer } = require('bare-buffer')

/**
* Process JSON request body
* @param {http.IncomingMessage} req
* @returns {Promise<Object>}
*/
const MAX_BODY_SIZE = 1 * 1024 * 1024 // 1 MB

const processJsonRequest = async (req) => {
return new Promise((resolve, reject) => {
let body = ''
const chunks = []
let received = 0
req.on('data', chunk => {
body += chunk.toString()
received += chunk.length
if (received > MAX_BODY_SIZE) {
req.destroy(new ApiError(413, 'Payload too large'))
return
}
chunks.push(chunk)
})
req.on('end', () => {
try {
const body = Buffer.concat(chunks, received).toString('utf8')
if (!body) {
resolve({})
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,13 @@ const handleRequest = async (req, res) => {
}

res.setHeader('Content-Type', 'application/json')
res.setHeader('Access-Control-Allow-Origin', '*')

const origin = req.headers.origin || ''
const allowedOrigin = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin) ? origin : ''
res.setHeader('Access-Control-Allow-Origin', allowedOrigin)
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
res.setHeader('Vary', 'Origin')

if (method === HTTP_METHODS.OPTIONS) {
res.statusCode = 204
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,28 @@ const logger = require('../utils/logger')
const fs = require('bare-fs')
const process = require('bare-process')

const path = require('bare-path')

const WHISPER_CPP_PATH = '/path/to/whisper.cpp/build/bin/whisper-cli'

const ALLOWED_DIRS = [
path.resolve('.'),
path.resolve('./models'),
path.resolve('./examples')
]

const validatePath = (filePath) => {
const resolved = path.resolve(filePath)
if (!fs.existsSync(resolved)) {
throw new Error('File not found')
}
const isAllowed = ALLOWED_DIRS.some(dir => resolved.startsWith(dir + path.sep) || resolved === dir)
if (!isAllowed) {
throw new Error('File path is outside allowed directories')
}
return resolved
}

const convertRawToWav = async (rawFilePath, wavFilePath) => {
return new Promise((resolve, reject) => {
const args = [
Expand All @@ -31,15 +51,17 @@ const convertRawToWav = async (rawFilePath, wavFilePath) => {
}

const runWhisperCppCli = async (audioFilePath, modelPath) => {
const wavFilePath = audioFilePath.replace('.raw', '.wav')
await convertRawToWav(audioFilePath, wavFilePath)
const resolvedAudio = validatePath(audioFilePath)
const resolvedModel = validatePath(modelPath)
const wavFilePath = resolvedAudio.replace(/\.raw$/, '.wav')
await convertRawToWav(resolvedAudio, wavFilePath)

return new Promise((resolve, reject) => {
let stdout = ''
let stderr = ''

const args = [
'-m', modelPath,
'-m', resolvedModel,
'-f', wavFilePath,
'--output-txt',
'--no-timestamps'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
'use strict'

const { InferenceArgsSchema } = require('../validation')
const { spawn } = require('bare-subprocess')
const logger = require('../utils/logger')
const fs = require('bare-fs')
const { Readable } = require('bare-stream')
const process = require('bare-process')
const path = require('bare-path')

const ALLOWED_LIBS = [
'@qvac/transcription-whispercpp'
]

const loadedModels = new Map()

const ALLOWED_AUDIO_DIRS = [
path.resolve('.'),
path.resolve('./models'),
path.resolve('./examples')
]

const validateFilePath = (filePath) => {
const resolved = path.resolve(filePath)
if (!fs.existsSync(resolved)) {
throw new Error('File not found')
}
const isAllowed = ALLOWED_AUDIO_DIRS.some(dir => resolved.startsWith(dir + path.sep) || resolved === dir)
if (!isAllowed) {
throw new Error('File path is outside allowed directories')
}
return resolved
}

const getPackageVersion = (lib) => {
try {
const packagePath = require.resolve(`${lib}/package`)
Expand All @@ -21,26 +42,6 @@ const getPackageVersion = (lib) => {
}
}

const ensurePackage = async (lib, requestedVersion) => {
const installed = getPackageVersion(lib)
if (installed && (!requestedVersion || installed === requestedVersion)) {
return installed
}
const versionSpec = requestedVersion ? `@${requestedVersion}` : ''
logger.info(`Installing ${lib}${versionSpec}...`)
await new Promise((resolve, reject) => {
const npm = spawn('npm', ['install', `${lib}${versionSpec}`], { stdio: 'inherit' })
npm
.on('exit', code => code === 0 ? resolve() : reject(new Error(`npm install ${lib}${versionSpec} failed (${code})`)))
.on('error', reject)
})
const newVersion = getPackageVersion(lib)
if (!newVersion) {
throw new Error(`Failed to verify installation of ${lib}${versionSpec}`)
}
return newVersion
}

class FakeLoader {
async start () {}
async stop () {}
Expand Down Expand Up @@ -70,9 +71,13 @@ const runAddon = async (payload) => {
const { inputs, whisper, config } =
InferenceArgsSchema.parse(payload)

const { lib: whisperLib, version: whisperVerReq } = whisper
const { lib: whisperLib } = whisper

if (!ALLOWED_LIBS.includes(whisperLib)) {
throw new Error('Unsupported library: ' + whisperLib + '. Allowed: ' + ALLOWED_LIBS.join(', '))
}

const whisperVersion = await ensurePackage(whisperLib, whisperVerReq)
const whisperVersion = getPackageVersion(whisperLib) || 'unknown'
const TranscriptionWhispercpp = require(whisperLib)

logger.info(`Running addon with ${inputs.length} inputs`)
Expand All @@ -93,6 +98,7 @@ const runAddon = async (payload) => {
if (!config.path) {
throw new Error('Model path is required in config')
}
validateFilePath(config.path)

const constructorArgs = {
loader: new FakeLoader(),
Expand Down Expand Up @@ -150,7 +156,8 @@ const runAddon = async (payload) => {
const runStart = process.hrtime()

for (const audioFilePath of inputs) {
const audioBuffer = fs.readFileSync(audioFilePath)
const resolvedAudioPath = validateFilePath(audioFilePath)
const audioBuffer = fs.readFileSync(resolvedAudioPath)
const segments = []

let audioStream
Expand Down
Loading