Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions apps/mobile/lib/secure-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import * as SecureStore from "expo-secure-store"

const availability: Promise<boolean> = SecureStore.isAvailableAsync().catch(() => false)

export const secureStorage = {
getItem: async (name: string): Promise<string | null> => {
if (await availability) {
const value = await SecureStore.getItemAsync(name)
if (value !== null) return value
const legacy = await AsyncStorage.getItem(name)
if (legacy !== null) {
await SecureStore.setItemAsync(name, legacy).catch(() => undefined)
await AsyncStorage.removeItem(name).catch(() => undefined)
}
return legacy
}
return await AsyncStorage.getItem(name)
},
setItem: async (name: string, value: string): Promise<void> => {
if (await availability) {
await SecureStore.setItemAsync(name, value)
await AsyncStorage.removeItem(name).catch(() => undefined)
return
}
await AsyncStorage.setItem(name, value)
},
removeItem: async (name: string): Promise<void> => {
if (await availability) {
await SecureStore.deleteItemAsync(name).catch(() => undefined)
}
await AsyncStorage.removeItem(name).catch(() => undefined)
},
}
1 change: 1 addition & 0 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"expo-linking": "^57.0.5",
"expo-notifications": "~57.0.10",
"expo-router": "^57.0.11",
"expo-secure-store": "~57.0.0",
"expo-speech-recognition": "^56.0.1",
"expo-splash-screen": "~57.0.5",
"expo-status-bar": "~57.0.1",
Expand Down
4 changes: 2 additions & 2 deletions apps/mobile/store/auth.store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import { create } from "zustand"
import { createJSONStorage, persist } from "zustand/middleware"
import { secureStorage } from "../lib/secure-storage"

type User = {
id: string
Expand Down Expand Up @@ -33,7 +33,7 @@ export const useAuth = create<AuthStore>()(
}),
{
name: "crosscode-auth",
storage: createJSONStorage(() => AsyncStorage),
storage: createJSONStorage(() => secureStorage),
}
)
)
9 changes: 7 additions & 2 deletions apps/mobile/store/connection.store.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import AsyncStorage from "@react-native-async-storage/async-storage"
import { create } from "zustand"
import { createJSONStorage, persist } from "zustand/middleware"
import { secureStorage } from "../lib/secure-storage"

let nextID = 1

Expand Down Expand Up @@ -77,7 +77,12 @@ export const useConnections = create<ConnectionStore>()(
}),
{
name: "crosscode-connections",
storage: createJSONStorage(() => AsyncStorage)
storage: createJSONStorage(() => secureStorage),
partialize: (state) => ({
connections: state.connections.map(({ healthy, ...rest }) => rest),
current: state.current,
activeConnections: state.activeConnections,
}),
}
)
)
2 changes: 1 addition & 1 deletion packages/crosscode/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export function ensureSessionToken(config: Config, project?: ProjectConfig): str
export function ensureProjectId(config: Config, project?: ProjectConfig): string {
const target = project ?? getProjectConfig(config)
if (!target.projectId) {
target.projectId = crypto.randomBytes(4).toString("hex")
target.projectId = crypto.randomBytes(16).toString("hex")
saveProjectConfig(config)
logCrosscode(`Project ID generated for ${process.cwd()}: ${target.projectId}`)
} else {
Expand Down
33 changes: 33 additions & 0 deletions packages/tunnel-server/src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,30 @@ import type { WebSocket } from "ws"
import { logger } from "./logger.js"
import { createQuestionPushObserver, createSsePushObserver } from "./push-events.js"

const RATE_LIMIT_WINDOW = 60_000
const MAX_REQUESTS_PER_WINDOW = 120
const MAX_RATE_LIMIT_KEYS = 10_000
const rateLimits = new Map<string, { count: number; resetAt: number }>()

function checkRateLimit(key: string): { allowed: boolean; retryAfter: number } {
const now = Date.now()
let limit = rateLimits.get(key)
if (!limit || now > limit.resetAt) {
if (rateLimits.size >= MAX_RATE_LIMIT_KEYS) {
for (const [k, v] of rateLimits) {
if (v.resetAt <= now) rateLimits.delete(k)
}
}
limit = { count: 0, resetAt: now + RATE_LIMIT_WINDOW }
rateLimits.set(key, limit)
}
limit.count++
return {
allowed: limit.count <= MAX_REQUESTS_PER_WINDOW,
retryAfter: Math.max(1, Math.ceil((limit.resetAt - now) / 1000)),
}
}

export function handleProxy(req: IncomingMessage, res: ServerResponse): void {
const url = req.url || "/"
const method = req.method || "GET"
Expand Down Expand Up @@ -48,6 +72,15 @@ export function handleProxy(req: IncomingMessage, res: ServerResponse): void {
return
}

const clientIp = req.socket.remoteAddress || "unknown"
const limit = checkRateLimit(`${projectId}:${clientIp}`)
if (!limit.allowed) {
logger.warn("Rate limit exceeded for tunnel", { projectId, path, method })
res.writeHead(429, { "Content-Type": "application/json", "Retry-After": String(limit.retryAfter) })
res.end(JSON.stringify({ error: "Too many requests. Please try again later." }))
return
}

const reqId = generateReqId()
recordRequestStart(projectId)
const hasAuth = !!req.headers["authorization"]
Expand Down
24 changes: 17 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading