2
0

🔥 Remove streamer Pages API endpoint

This commit is contained in:
Baptiste Arnaud
2023-10-06 16:34:10 +02:00
parent b232a9495e
commit bf1f657642
31 changed files with 145 additions and 231 deletions

View File

@@ -0,0 +1,10 @@
import { decryptV1 } from './decryptV1'
import { decryptV2 } from './decryptV2'
export const decrypt = async (
encryptedData: string,
ivHex: string
): Promise<object> => {
if (ivHex.length !== 24) return decryptV1(encryptedData, ivHex)
return decryptV2(encryptedData, ivHex)
}

View File

@@ -0,0 +1,21 @@
import { env } from '@typebot.io/env'
import { createDecipheriv } from 'crypto'
const algorithm = 'aes-256-gcm'
const secretKey = env.ENCRYPTION_SECRET
export const decryptV1 = (encryptedData: string, auth: string): object => {
if (!secretKey) throw new Error(`ENCRYPTION_SECRET is not in environment`)
const [iv, tag] = auth.split('.')
const decipher = createDecipheriv(
algorithm,
secretKey,
Buffer.from(iv, 'hex')
)
decipher.setAuthTag(Buffer.from(tag, 'hex'))
return JSON.parse(
(
decipher.update(Buffer.from(encryptedData, 'hex')) + decipher.final('hex')
).toString()
)
}

View File

@@ -0,0 +1,35 @@
import { env } from '@typebot.io/env'
const algorithm = 'AES-GCM'
const secretKey = env.ENCRYPTION_SECRET
export const decryptV2 = async (
encryptedData: string,
ivHex: string
): Promise<object> => {
if (!secretKey) throw new Error('ENCRYPTION_SECRET is not in environment')
const iv = new Uint8Array(
ivHex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) ?? []
)
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secretKey),
algorithm,
false,
['decrypt']
)
const encryptedBuffer = new Uint8Array(
Array.from(atob(encryptedData)).map((char) => char.charCodeAt(0))
)
const decryptedBuffer = await crypto.subtle.decrypt(
{ name: algorithm, iv },
key,
encryptedBuffer
)
const decryptedData = new TextDecoder().decode(decryptedBuffer)
return JSON.parse(decryptedData)
}

View File

@@ -0,0 +1,39 @@
import { env } from '@typebot.io/env'
const algorithm = 'AES-GCM'
const secretKey = env.ENCRYPTION_SECRET
export const encrypt = async (
data: object
): Promise<{ encryptedData: string; iv: string }> => {
if (!secretKey) throw new Error('ENCRYPTION_SECRET is not in environment')
const iv = crypto.getRandomValues(new Uint8Array(12))
const encodedData = new TextEncoder().encode(JSON.stringify(data))
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secretKey),
algorithm,
false,
['encrypt']
)
const encryptedBuffer = await crypto.subtle.encrypt(
{ name: algorithm, iv },
key,
encodedData
)
const encryptedData = btoa(
String.fromCharCode.apply(null, Array.from(new Uint8Array(encryptedBuffer)))
)
const ivHex = Array.from(iv)
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('')
return {
encryptedData,
iv: ivHex,
}
}