| import express from 'express'; |
| import fetch from 'node-fetch'; |
| import fs from 'node:fs'; |
| import path from 'node:path'; |
| import { forwardFetchResponse } from '../util.js'; |
|
|
| export const router = express.Router(); |
|
|
| function getHiddenPrompts() { |
| const HIDDEN_PROMPTS_FILE = path.join(globalThis.DATA_ROOT || '', 'hidden_prompts.json'); |
| try { |
| if (fs.existsSync(HIDDEN_PROMPTS_FILE)) { |
| return JSON.parse(fs.readFileSync(HIDDEN_PROMPTS_FILE, 'utf8')); |
| } |
| } catch (err) { |
| console.error('Error reading hidden prompts:', err); |
| } |
| return {}; |
| } |
|
|
| router.post('/', async (req, res) => { |
| const { target_url, hidden_prompt_id, ...llm_params } = req.body; |
|
|
| if (!target_url) { |
| return res.status(400).send('Missing target_url'); |
| } |
|
|
| const hiddenPrompts = getHiddenPrompts(); |
| const hiddenPrompt = hiddenPrompts[hidden_prompt_id]; |
|
|
| if (hiddenPrompt && llm_params.messages) { |
| console.log(`Injecting hidden prompt: ${hidden_prompt_id}`); |
| |
| llm_params.messages.unshift({ |
| role: hiddenPrompt.role || 'system', |
| content: hiddenPrompt.prompt |
| }); |
| } |
|
|
| try { |
| const headers = { ...req.headers }; |
| |
| delete headers.host; |
| delete headers['content-length']; |
| delete headers['x-csrf-token']; |
| delete headers.cookie; |
|
|
| const response = await fetch(target_url, { |
| method: 'POST', |
| headers: headers, |
| body: JSON.stringify(llm_params), |
| }); |
|
|
| forwardFetchResponse(response, res); |
| } catch (error) { |
| console.error('Error in secure-generate proxy:', error); |
| res.status(500).send('Error in secure-generate proxy: ' + error.message); |
| } |
| }); |
|
|
| router.get('/list', (req, res) => { |
| const hiddenPrompts = getHiddenPrompts(); |
| const list = Object.entries(hiddenPrompts).map(([id, data]) => ({ |
| id, |
| label: data.name || id |
| })); |
| res.json(list); |
| }); |
|
|