-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecrypt-proxy.ts
More file actions
237 lines (204 loc) · 6.58 KB
/
Copy pathdecrypt-proxy.ts
File metadata and controls
237 lines (204 loc) · 6.58 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
// Decrypt proxy: decrypts API responses so the AI can read plaintext.
// You hold the key; the AI only needs an expirable token when DECRYPT_TOKEN_SECRET is set.
//
// Without token (local dev):
// ENCRYPTION_KEY=your-key bun scripts/decrypt-proxy.ts
//
// With expirable token (give AI only the token, not the key):
// ENCRYPTION_KEY=... DECRYPT_TOKEN_SECRET=... bun scripts/decrypt-proxy.ts
// Issue token: DECRYPT_TOKEN_SECRET=... npx tsx scripts/issue-decrypt-token.ts --expires-in 24h
// AI calls proxy with header: X-Decrypt-Token: <token>
import { createHmac } from "crypto"
import { createServer, IncomingMessage, ServerResponse } from "http"
const PROXY_PORT = 3001
const TARGET_HOST = process.env.TARGET_HOST || "http://localhost:3030"
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || ""
const DECRYPT_TOKEN_SECRET = process.env.DECRYPT_TOKEN_SECRET || ""
if (!ENCRYPTION_KEY) {
console.error("❌ ENCRYPTION_KEY environment variable is required")
process.exit(1)
}
const AUD = "contexter-decrypt"
function base64UrlDecode(str: string): Buffer {
const base64 = str.replace(/-/g, "+").replace(/_/g, "/")
const pad = base64.length % 4
const padded = pad ? base64 + "=".repeat(4 - pad) : base64
return Buffer.from(padded, "base64")
}
function verifyDecryptToken(token: string): boolean {
if (!DECRYPT_TOKEN_SECRET) {
return true
}
if (!token) {
return false
}
const parts = token.split(".")
if (parts.length !== 3) {
return false
}
const [headerB64, payloadB64, sigB64] = parts
const signatureInput = `${headerB64}.${payloadB64}`
const expectedSig = createHmac("sha256", DECRYPT_TOKEN_SECRET)
.update(signatureInput)
.digest()
const expectedB64 = expectedSig
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "")
if (sigB64 !== expectedB64) {
return false
}
let payload: { aud?: string; exp?: number }
try {
payload = JSON.parse(base64UrlDecode(payloadB64).toString("utf8"))
} catch {
return false
}
if (payload.aud !== AUD || typeof payload.exp !== "number") {
return false
}
if (payload.exp < Math.floor(Date.now() / 1000)) {
return false
}
return true
}
const ALGORITHM = "AES-GCM"
const KEY_LENGTH = 256
const PBKDF2_ITERATIONS = 100000
const SALT = "contexter-e2e-v1"
const ENCRYPTED_PREFIX = "enc:v1:"
const MAX_DEPTH = 2
async function deriveKey(passphrase: string): Promise<CryptoKey> {
const encoder = new TextEncoder()
const passphraseKey = await crypto.subtle.importKey(
"raw",
encoder.encode(passphrase),
"PBKDF2",
false,
["deriveBits", "deriveKey"]
)
return crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: encoder.encode(SALT),
iterations: PBKDF2_ITERATIONS,
hash: "SHA-256",
},
passphraseKey,
{ name: ALGORITHM, length: KEY_LENGTH },
false,
["decrypt"]
)
}
async function decryptText(
ciphertext: string,
passphrase: string
): Promise<string | null> {
if (!ciphertext || !passphrase) {
return ciphertext
}
if (!ciphertext.startsWith(ENCRYPTED_PREFIX)) {
return ciphertext
}
const parts = ciphertext.slice(ENCRYPTED_PREFIX.length).split(":")
if (parts.length !== 3) {
return null
}
const [ivB64, authTagB64, encryptedB64] = parts
const iv = Uint8Array.from(atob(ivB64), (c) => c.charCodeAt(0))
const authTag = Uint8Array.from(atob(authTagB64), (c) => c.charCodeAt(0))
const encrypted = Uint8Array.from(atob(encryptedB64), (c) => c.charCodeAt(0))
const combined = new Uint8Array(encrypted.length + authTag.length)
combined.set(encrypted)
combined.set(authTag, encrypted.length)
const key = await deriveKey(passphrase)
const decrypted = await crypto.subtle.decrypt(
{ name: ALGORITHM, iv },
key,
combined
)
return new TextDecoder().decode(decrypted)
}
async function decryptObject(obj: unknown, depth = 0): Promise<unknown> {
if (obj === null || obj === undefined) {
return obj
}
if (Array.isArray(obj)) {
return Promise.all(obj.map((item) => decryptObject(item, depth)))
}
if (typeof obj === "object") {
const result: Record<string, unknown> = {}
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "string" && value.startsWith(ENCRYPTED_PREFIX)) {
result[key] = await decryptText(value, ENCRYPTION_KEY)
} else if (
typeof value === "object" &&
value !== null &&
depth < MAX_DEPTH
) {
result[key] = await decryptObject(value, depth + 1)
} else {
result[key] = value
}
}
return result
}
return obj
}
async function handleRequest(req: IncomingMessage, res: ServerResponse) {
const url = new URL(req.url || "/", `http://localhost:${PROXY_PORT}`)
const targetUrl = `${TARGET_HOST}${url.pathname}${url.search}`
console.log(`→ ${req.method} ${url.pathname}`)
const headers: Record<string, string> = {}
for (const [key, value] of Object.entries(req.headers)) {
if (value && key.toLowerCase() !== "host") {
headers[key] = Array.isArray(value) ? value.join(", ") : value
}
}
let body: string | undefined
if (req.method === "POST" || req.method === "PUT" || req.method === "PATCH") {
body = await new Promise<string>((resolve) => {
let data = ""
req.on("data", (chunk) => (data += chunk))
req.on("end", () => resolve(data))
})
}
const response = await fetch(targetUrl, {
method: req.method,
headers,
body,
})
const contentType = response.headers.get("content-type") || ""
if (contentType.includes("application/json")) {
const json = await response.json()
const decrypted = await decryptObject(json)
res.writeHead(response.status, {
"Content-Type": "application/json",
"X-Decrypted-By": "decrypt-proxy",
})
res.end(JSON.stringify(decrypted, null, 2))
console.log(`← ${response.status} (decrypted)`)
} else {
const buffer = await response.arrayBuffer()
res.writeHead(response.status, {
"Content-Type": contentType,
})
res.end(Buffer.from(buffer))
console.log(`← ${response.status} (passthrough)`)
}
}
const server = createServer((req, res) => {
handleRequest(req, res).catch((err) => {
console.error("Error:", err.message)
res.writeHead(500, { "Content-Type": "application/json" })
res.end(JSON.stringify({ error: err.message }))
})
})
server.listen(PROXY_PORT, () => {
console.log(`\n🔓 Decrypt proxy running on http://localhost:${PROXY_PORT}`)
console.log(` Forwarding to ${TARGET_HOST}`)
console.log(
`\n Example: curl http://localhost:${PROXY_PORT}/api/whatsapp/messages\n`
)
})