File size: 2,095 Bytes
87fd35f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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}`);
        // Inject at the beginning of the messages array
        llm_params.messages.unshift({
            role: hiddenPrompt.role || 'system',
            content: hiddenPrompt.prompt
        });
    }

    try {
        const headers = { ...req.headers };
        // Remove host and other potentially problematic 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);
});