Skip to content

Commit

Permalink
fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
polymorpher committed Nov 12, 2023
1 parent b6f6a8a commit 021a976
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 19 deletions.
13 changes: 8 additions & 5 deletions voice/relay/src/routes/soft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Router, type Request, type Response, type NextFunction } from 'express'
import { HttpStatusCode } from 'axios'
import rateLimit, { type Options as RLOptions, type RateLimitRequestHandler } from 'express-rate-limit'
import { BlockedDeviceIds, BlockedIps, OpenAIDistributedKeys } from '../config/index.js'
import { encrypt, hexString, stringToBytes } from '../utils.js'
import { encrypt, hexString, hexView, stringToBytes } from '../utils.js'
import { hash as sha256 } from 'fast-sha256'
const router: Router = Router()

Expand All @@ -27,11 +27,13 @@ const parseDeviceToken = (req: Request, res: Response, next: NextFunction): any
res.status(HttpStatusCode.Forbidden).json({ error: 'device unsupported', code: 100 })
return
}
if (BlockedDeviceIds.includes(deviceToken)) {
const deviceTokenHash = hexView(sha256(stringToBytes(deviceToken)))
if (BlockedDeviceIds.includes(deviceTokenHash)) {
res.status(HttpStatusCode.Forbidden).json({ error: 'device banned', code: 101 })
return
}
req.deviceToken = deviceToken
req.deviceTokenHash = deviceTokenHash
next()
}

Expand All @@ -51,12 +53,13 @@ router.get('/health', (req, res) => {

router.get('/key', parseDeviceToken, checkIpBan, deviceLimiter(), ipLimiter(), (req, res) => {
// TODO: validate the device token, https://developer.apple.com/documentation/devicecheck/accessing_and_modifying_per-device_data
const deviceToken = req.deviceToken
const numKeys = BigInt(OpenAIDistributedKeys.length)
const h = hexString(sha256(stringToBytes(deviceToken)))
const keyIndex = Number(BigInt(h) % numKeys)
const keyIndex = Number(BigInt('0x' + req.deviceTokenHash) % numKeys)
const key = OpenAIDistributedKeys[keyIndex]
const encryptedKey = encrypt(key)
const encoded = encryptedKey.toString('base64')

console.log(`[deviceTokenHash=${req.deviceTokenHash}][ip=${req.clientIp}] Provided encryptedKey ${encoded}`)
res.json({ key: encryptedKey.toString('base64') })
})

Expand Down
5 changes: 4 additions & 1 deletion voice/relay/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ export function chunkstr (str: string, size: number): string[] {
const aesKey = sha256(stringToBytes(SharedEncryptionSecret)).slice(0, 32)
const aesIv = sha256(stringToBytes(SharedEncryptionIV)).slice(0, 16)

// console.log('aesKey', aesKey)
// console.log('aesIv', aesIv)

export function encrypt (s: string): Buffer {
const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, aesIv)
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, aesIv)
return Buffer.concat([cipher.update(s, 'utf8'), cipher.final()])
}
1 change: 1 addition & 0 deletions voice/relay/types/express/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ declare global {
namespace Express {
interface Request {
deviceToken: string
deviceTokenHash: string
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion voice/voice-ai/x/Actions/ActionsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import StoreKit
import SwiftUI

struct ActionsView: View {
let config = AppConfig()
let config = AppConfig.shared

@ObservedObject private var timerManager = TimerManager.shared

Expand Down
24 changes: 12 additions & 12 deletions voice/voice-ai/x/AppConfigration/AppConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,20 @@ class AppConfig {

init() {
self.loadConfiguration()
Task {
await self.requestOpenAIKey()
}
}

private func decrypt(base64EncodedEncryptedKey: String) throws -> String {
let d = Data(base64Encoded: base64EncodedEncryptedKey)
guard let d = d else {
throw NSError(domain: "Invalid encoded encrypted key", code: -1)
}
let encryptedKey = String(data: d, encoding: .utf8)
let encryptedKey = Data(base64Encoded: base64EncodedEncryptedKey)
guard let encryptedKey = encryptedKey else {
throw NSError(domain: "Malformed key encoding", code: -2)
throw NSError(domain: "Invalid encoded encrypted key", code: -1)
}
let iv: [UInt8] = Array(self.sharedEncryptionIV!.utf8)
let sharedKey: [UInt8] = Array(self.sharedEncryptionSecret!.utf8)
let aes = try AES(key: sharedKey, blockMode: GCM(iv: iv))

let iv = [UInt8](self.sharedEncryptionIV!.data(using: .utf8)!.sha256()[0..<16])
let sharedKey = [UInt8](self.sharedEncryptionSecret!.data(using: .utf8)!.sha256()[0..<32])
let aes = try AES(key: sharedKey, blockMode: CBC(iv: iv))
let dBytes = try aes.decrypt(encryptedKey.bytes)
let dKey = String(data: Data(dBytes), encoding: .utf8)
guard let key = dKey else {
Expand All @@ -50,7 +50,7 @@ class AppConfig {
}
let s = URLSession(configuration: .default)
guard let url = URL(string: "\(relayUrl)/key") else {
let error = NSError(domain: "Invalid Relay URL", code: -1, userInfo: nil)
print("Invalid Relay URL")
SentrySDK.capture(message: "Invalid Relay URL")
return
}
Expand All @@ -66,7 +66,7 @@ class AppConfig {
}
var r = URLRequest(url: url)
r.setValue(token, forHTTPHeaderField: "X-DEVICE-TOKEN")
s.dataTask(with: r) { data, _, err in
let t = s.dataTask(with: r) { data, _, err in
if let err = err {
print("[AppConfig][requestOpenAIKey] cannot get key", err)
SentrySDK.capture(message: "Cannot get key. Error: \(err)")
Expand All @@ -89,7 +89,7 @@ class AppConfig {
SentrySDK.capture(message: "[AppConfig][requestOpenAIKey] error processing key response \(error)")
}
}
// s.dataTask(with: "")
t.resume()
}

private func loadConfiguration() {
Expand Down

0 comments on commit 021a976

Please sign in to comment.