mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
feat: add namespace-based multi-user isolation
Implement namespace support across sessions, machines, and users for multi-user server deployments. Add access control with specific error reasons (namespace-missing, access-denied, not-found) and database schema updates with namespace columns and indexes.
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import type { Server, Socket } from 'socket.io'
|
||||
import { z } from 'zod'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { Store } from '../../store'
|
||||
import type { Store, StoredMachine, StoredSession } from '../../store'
|
||||
import { RpcRegistry } from '../rpcRegistry'
|
||||
import type { SyncEvent } from '../../sync/syncEngine'
|
||||
import { extractTodoWriteTodosFromMessageContent } from '../../sync/todos'
|
||||
import { TerminalRegistry } from '../terminalRegistry'
|
||||
import type { SocketServer, SocketWithData } from '../socketTypes'
|
||||
|
||||
type SessionAlivePayload = {
|
||||
sid: string
|
||||
@@ -89,7 +89,7 @@ const terminalErrorSchema = z.object({
|
||||
})
|
||||
|
||||
export type CliHandlersDeps = {
|
||||
io: Server
|
||||
io: SocketServer
|
||||
store: Store
|
||||
rpcRegistry: RpcRegistry
|
||||
terminalRegistry: TerminalRegistry
|
||||
@@ -99,21 +99,64 @@ export type CliHandlersDeps = {
|
||||
onWebappEvent?: (event: SyncEvent) => void
|
||||
}
|
||||
|
||||
export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void {
|
||||
type AccessErrorReason = 'namespace-missing' | 'access-denied' | 'not-found'
|
||||
type AccessResult<T> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; reason: AccessErrorReason }
|
||||
|
||||
export function registerCliHandlers(socket: SocketWithData, deps: CliHandlersDeps): void {
|
||||
const { io, store, rpcRegistry, terminalRegistry, onSessionAlive, onSessionEnd, onMachineAlive, onWebappEvent } = deps
|
||||
const terminalNamespace = io.of('/terminal')
|
||||
const namespace = typeof socket.data.namespace === 'string' ? socket.data.namespace : null
|
||||
|
||||
const resolveSessionAccess = (sessionId: string): AccessResult<StoredSession> => {
|
||||
if (!namespace) {
|
||||
return { ok: false, reason: 'namespace-missing' }
|
||||
}
|
||||
const session = store.getSessionByNamespace(sessionId, namespace)
|
||||
if (session) {
|
||||
return { ok: true, value: session }
|
||||
}
|
||||
if (store.getSession(sessionId)) {
|
||||
return { ok: false, reason: 'access-denied' }
|
||||
}
|
||||
return { ok: false, reason: 'not-found' }
|
||||
}
|
||||
|
||||
const resolveMachineAccess = (machineId: string): AccessResult<StoredMachine> => {
|
||||
if (!namespace) {
|
||||
return { ok: false, reason: 'namespace-missing' }
|
||||
}
|
||||
const machine = store.getMachineByNamespace(machineId, namespace)
|
||||
if (machine) {
|
||||
return { ok: true, value: machine }
|
||||
}
|
||||
if (store.getMachine(machineId)) {
|
||||
return { ok: false, reason: 'access-denied' }
|
||||
}
|
||||
return { ok: false, reason: 'not-found' }
|
||||
}
|
||||
|
||||
const auth = socket.handshake.auth as Record<string, unknown> | undefined
|
||||
const sessionId = typeof auth?.sessionId === 'string' ? auth.sessionId : null
|
||||
if (sessionId) {
|
||||
if (sessionId && resolveSessionAccess(sessionId).ok) {
|
||||
socket.join(`session:${sessionId}`)
|
||||
}
|
||||
|
||||
const machineId = typeof auth?.machineId === 'string' ? auth.machineId : null
|
||||
if (machineId) {
|
||||
if (machineId && resolveMachineAccess(machineId).ok) {
|
||||
socket.join(`machine:${machineId}`)
|
||||
}
|
||||
|
||||
const emitAccessError = (scope: 'session' | 'machine', id: string, reason: AccessErrorReason) => {
|
||||
const message = reason === 'access-denied'
|
||||
? `${scope} access denied`
|
||||
: reason === 'not-found'
|
||||
? `${scope} not found`
|
||||
: 'Namespace missing'
|
||||
socket.emit('error', { message, code: reason, scope, id })
|
||||
}
|
||||
|
||||
socket.on('rpc-register', (data: unknown) => {
|
||||
const parsed = rpcRegisterSchema.safeParse(data)
|
||||
if (!parsed.success) {
|
||||
@@ -161,11 +204,18 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
})()
|
||||
: raw
|
||||
|
||||
const sessionAccess = resolveSessionAccess(sid)
|
||||
if (!sessionAccess.ok) {
|
||||
emitAccessError('session', sid, sessionAccess.reason)
|
||||
return
|
||||
}
|
||||
const session = sessionAccess.value
|
||||
|
||||
const msg = store.addMessage(sid, content, localId)
|
||||
|
||||
const todos = extractTodoWriteTodosFromMessageContent(content)
|
||||
if (todos) {
|
||||
const updated = store.setSessionTodos(sid, todos, msg.createdAt)
|
||||
const updated = store.setSessionTodos(sid, todos, msg.createdAt, session.namespace)
|
||||
if (updated) {
|
||||
onWebappEvent?.({ type: 'session-updated', sessionId: sid, data: { sid } })
|
||||
}
|
||||
@@ -211,7 +261,13 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
}
|
||||
|
||||
const { sid, metadata, expectedVersion } = parsed.data
|
||||
const result = store.updateSessionMetadata(sid, metadata, expectedVersion)
|
||||
const sessionAccess = resolveSessionAccess(sid)
|
||||
if (!sessionAccess.ok) {
|
||||
cb({ result: 'error', reason: sessionAccess.reason })
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateSessionMetadata(sid, metadata, expectedVersion, sessionAccess.value.namespace)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, metadata: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
@@ -245,7 +301,13 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
}
|
||||
|
||||
const { sid, agentState, expectedVersion } = parsed.data
|
||||
const result = store.updateSessionAgentState(sid, agentState, expectedVersion)
|
||||
const sessionAccess = resolveSessionAccess(sid)
|
||||
if (!sessionAccess.ok) {
|
||||
cb({ result: 'error', reason: sessionAccess.reason })
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateSessionAgentState(sid, agentState, expectedVersion, sessionAccess.value.namespace)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, agentState: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
@@ -275,6 +337,11 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
if (!data || typeof data.sid !== 'string' || typeof data.time !== 'number') {
|
||||
return
|
||||
}
|
||||
const sessionAccess = resolveSessionAccess(data.sid)
|
||||
if (!sessionAccess.ok) {
|
||||
emitAccessError('session', data.sid, sessionAccess.reason)
|
||||
return
|
||||
}
|
||||
onSessionAlive?.(data)
|
||||
})
|
||||
|
||||
@@ -282,6 +349,11 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
if (!data || typeof data.sid !== 'string' || typeof data.time !== 'number') {
|
||||
return
|
||||
}
|
||||
const sessionAccess = resolveSessionAccess(data.sid)
|
||||
if (!sessionAccess.ok) {
|
||||
emitAccessError('session', data.sid, sessionAccess.reason)
|
||||
return
|
||||
}
|
||||
onSessionEnd?.(data)
|
||||
})
|
||||
|
||||
@@ -289,6 +361,11 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
if (!data || typeof data.machineId !== 'string' || typeof data.time !== 'number') {
|
||||
return
|
||||
}
|
||||
const machineAccess = resolveMachineAccess(data.machineId)
|
||||
if (!machineAccess.ok) {
|
||||
emitAccessError('machine', data.machineId, machineAccess.reason)
|
||||
return
|
||||
}
|
||||
onMachineAlive?.(data)
|
||||
})
|
||||
|
||||
@@ -300,7 +377,13 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
}
|
||||
|
||||
const { machineId: id, metadata, expectedVersion } = parsed.data
|
||||
const result = store.updateMachineMetadata(id, metadata, expectedVersion)
|
||||
const machineAccess = resolveMachineAccess(id)
|
||||
if (!machineAccess.ok) {
|
||||
cb({ result: 'error', reason: machineAccess.reason })
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateMachineMetadata(id, metadata, expectedVersion, machineAccess.value.namespace)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, metadata: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
@@ -334,7 +417,13 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
}
|
||||
|
||||
const { machineId: id, daemonState, expectedVersion } = parsed.data
|
||||
const result = store.updateMachineDaemonState(id, daemonState, expectedVersion)
|
||||
const machineAccess = resolveMachineAccess(id)
|
||||
if (!machineAccess.ok) {
|
||||
cb({ result: 'error', reason: machineAccess.reason })
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateMachineDaemonState(id, daemonState, expectedVersion, machineAccess.value.namespace)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, daemonState: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
@@ -381,6 +470,11 @@ export function registerCliHandlers(socket: Socket, deps: CliHandlersDeps): void
|
||||
if (payload.sessionId !== entry.sessionId) {
|
||||
return
|
||||
}
|
||||
const sessionAccess = resolveSessionAccess(payload.sessionId)
|
||||
if (!sessionAccess.ok) {
|
||||
emitAccessError('session', payload.sessionId, sessionAccess.reason)
|
||||
return
|
||||
}
|
||||
const terminalSocket = terminalNamespace.sockets.get(entry.socketId)
|
||||
if (!terminalSocket) {
|
||||
return
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { Server, Socket } from 'socket.io'
|
||||
import { registerTerminalHandlers } from './terminal'
|
||||
import { TerminalRegistry } from '../terminalRegistry'
|
||||
import type { SocketServer, SocketWithData } from '../socketTypes'
|
||||
|
||||
type EmittedEvent = {
|
||||
event: string
|
||||
@@ -74,12 +74,13 @@ function createHarness(options?: {
|
||||
}): Harness {
|
||||
const io = new FakeServer()
|
||||
const terminalSocket = new FakeSocket('terminal-socket')
|
||||
terminalSocket.data.namespace = 'default'
|
||||
const terminalRegistry = new TerminalRegistry({ idleTimeoutMs: 0 })
|
||||
const cliNamespace = io.of('/cli')
|
||||
|
||||
registerTerminalHandlers(terminalSocket as unknown as Socket, {
|
||||
io: io as unknown as Server,
|
||||
getSession: () => ({ active: options?.sessionActive ?? true }),
|
||||
registerTerminalHandlers(terminalSocket as unknown as SocketWithData, {
|
||||
io: io as unknown as SocketServer,
|
||||
getSession: () => ({ active: options?.sessionActive ?? true, namespace: 'default' }),
|
||||
terminalRegistry,
|
||||
maxTerminalsPerSocket: options?.maxTerminalsPerSocket ?? 4,
|
||||
maxTerminalsPerSession: options?.maxTerminalsPerSession ?? 4
|
||||
@@ -89,6 +90,7 @@ function createHarness(options?: {
|
||||
}
|
||||
|
||||
function connectCliSocket(cliNamespace: FakeNamespace, cliSocket: FakeSocket, sessionId: string): void {
|
||||
cliSocket.data.namespace = 'default'
|
||||
cliNamespace.sockets.set(cliSocket.id, cliSocket)
|
||||
const roomId = `session:${sessionId}`
|
||||
const room = cliNamespace.adapter.rooms.get(roomId) ?? new Set<string>()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Server, Socket } from 'socket.io'
|
||||
import { z } from 'zod'
|
||||
import type { TerminalRegistry, TerminalRegistryEntry } from '../terminalRegistry'
|
||||
import type { SocketServer, SocketWithData } from '../socketTypes'
|
||||
|
||||
const terminalCreateSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
@@ -25,16 +25,17 @@ const terminalCloseSchema = z.object({
|
||||
})
|
||||
|
||||
export type TerminalHandlersDeps = {
|
||||
io: Server
|
||||
getSession: (sessionId: string) => { active: boolean } | null
|
||||
io: SocketServer
|
||||
getSession: (sessionId: string) => { active: boolean; namespace: string } | null
|
||||
terminalRegistry: TerminalRegistry
|
||||
maxTerminalsPerSocket: number
|
||||
maxTerminalsPerSession: number
|
||||
}
|
||||
|
||||
export function registerTerminalHandlers(socket: Socket, deps: TerminalHandlersDeps): void {
|
||||
export function registerTerminalHandlers(socket: SocketWithData, deps: TerminalHandlersDeps): void {
|
||||
const { io, getSession, terminalRegistry, maxTerminalsPerSocket, maxTerminalsPerSession } = deps
|
||||
const cliNamespace = io.of('/cli')
|
||||
const namespace = typeof socket.data.namespace === 'string' ? socket.data.namespace : null
|
||||
|
||||
const emitTerminalError = (terminalId: string, message: string) => {
|
||||
socket.emit('terminal:error', { terminalId, message })
|
||||
@@ -48,9 +49,9 @@ export function registerTerminalHandlers(socket: Socket, deps: TerminalHandlersD
|
||||
return entry
|
||||
}
|
||||
|
||||
const resolveCliSocket = (entry: TerminalRegistryEntry, reportError: boolean): Socket | null => {
|
||||
const resolveCliSocket = (entry: TerminalRegistryEntry, reportError: boolean): SocketWithData | null => {
|
||||
const cliSocket = cliNamespace.sockets.get(entry.cliSocketId)
|
||||
if (!cliSocket) {
|
||||
if (!cliSocket || cliSocket.data.namespace !== namespace) {
|
||||
terminalRegistry.remove(entry.terminalId)
|
||||
if (reportError) {
|
||||
emitTerminalError(entry.terminalId, 'CLI disconnected.')
|
||||
@@ -62,7 +63,7 @@ export function registerTerminalHandlers(socket: Socket, deps: TerminalHandlersD
|
||||
|
||||
const emitCloseToCli = (entry: TerminalRegistryEntry): void => {
|
||||
const cliSocket = cliNamespace.sockets.get(entry.cliSocketId)
|
||||
if (!cliSocket) {
|
||||
if (!cliSocket || cliSocket.data.namespace !== namespace) {
|
||||
return
|
||||
}
|
||||
cliSocket.emit('terminal:close', {
|
||||
@@ -77,8 +78,9 @@ export function registerTerminalHandlers(socket: Socket, deps: TerminalHandlersD
|
||||
return null
|
||||
}
|
||||
for (const socketId of room) {
|
||||
if (cliNamespace.sockets.has(socketId)) {
|
||||
return socketId
|
||||
const cliSocket = cliNamespace.sockets.get(socketId)
|
||||
if (cliSocket && cliSocket.data.namespace === namespace) {
|
||||
return cliSocket.id
|
||||
}
|
||||
}
|
||||
return null
|
||||
@@ -92,7 +94,7 @@ export function registerTerminalHandlers(socket: Socket, deps: TerminalHandlersD
|
||||
|
||||
const { sessionId, terminalId, cols, rows } = parsed.data
|
||||
const session = getSession(sessionId)
|
||||
if (!session || !session.active) {
|
||||
if (!namespace || !session || session.namespace !== namespace || !session.active) {
|
||||
emitTerminalError(terminalId, 'Session is inactive or unavailable.')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import { Server as Engine } from '@socket.io/bun-engine'
|
||||
import { Server } from 'socket.io'
|
||||
import { Server, type DefaultEventsMap } from 'socket.io'
|
||||
import { jwtVerify } from 'jose'
|
||||
import { z } from 'zod'
|
||||
import type { Store } from '../store'
|
||||
import { configuration } from '../configuration'
|
||||
import { safeCompareStrings } from '../utils/crypto'
|
||||
import { parseAccessToken } from '../utils/accessToken'
|
||||
import { registerCliHandlers } from './handlers/cli'
|
||||
import { registerTerminalHandlers } from './handlers/terminal'
|
||||
import { RpcRegistry } from './rpcRegistry'
|
||||
import type { SyncEvent } from '../sync/syncEngine'
|
||||
import { TerminalRegistry } from './terminalRegistry'
|
||||
import type { SocketData, SocketServer } from './socketTypes'
|
||||
|
||||
const jwtPayloadSchema = z.object({
|
||||
uid: z.number()
|
||||
uid: z.number(),
|
||||
ns: z.string()
|
||||
})
|
||||
|
||||
const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60_000
|
||||
@@ -30,7 +33,7 @@ function resolveEnvNumber(name: string, fallback: number): number {
|
||||
export type SocketServerDeps = {
|
||||
store: Store
|
||||
jwtSecret: Uint8Array
|
||||
getSession?: (sessionId: string) => { active: boolean } | null
|
||||
getSession?: (sessionId: string) => { active: boolean; namespace: string } | null
|
||||
onWebappEvent?: (event: SyncEvent) => void
|
||||
onSessionAlive?: (payload: { sid: string; time: number; thinking?: boolean; mode?: 'local' | 'remote' }) => void
|
||||
onSessionEnd?: (payload: { sid: string; time: number }) => void
|
||||
@@ -38,14 +41,14 @@ export type SocketServerDeps = {
|
||||
}
|
||||
|
||||
export function createSocketServer(deps: SocketServerDeps): {
|
||||
io: Server
|
||||
io: SocketServer
|
||||
engine: Engine
|
||||
rpcRegistry: RpcRegistry
|
||||
} {
|
||||
const corsOrigins = configuration.corsOrigins
|
||||
const allowAllOrigins = corsOrigins.includes('*')
|
||||
|
||||
const io = new Server({
|
||||
const io = new Server<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, SocketData>({
|
||||
cors: {
|
||||
origin: (origin, callback) => {
|
||||
if (!origin) {
|
||||
@@ -94,9 +97,11 @@ export function createSocketServer(deps: SocketServerDeps): {
|
||||
cliNs.use((socket, next) => {
|
||||
const auth = socket.handshake.auth as Record<string, unknown> | undefined
|
||||
const token = typeof auth?.token === 'string' ? auth.token : null
|
||||
if (!safeCompareStrings(token, configuration.cliApiToken)) {
|
||||
const parsedToken = token ? parseAccessToken(token) : null
|
||||
if (!parsedToken || !safeCompareStrings(parsedToken.baseToken, configuration.cliApiToken)) {
|
||||
return next(new Error('Invalid token'))
|
||||
}
|
||||
socket.data.namespace = parsedToken.namespace
|
||||
next()
|
||||
})
|
||||
cliNs.on('connection', (socket) => registerCliHandlers(socket, {
|
||||
@@ -124,6 +129,7 @@ export function createSocketServer(deps: SocketServerDeps): {
|
||||
return next(new Error('Invalid token payload'))
|
||||
}
|
||||
socket.data.userId = parsed.data.uid
|
||||
socket.data.namespace = parsed.data.ns
|
||||
next()
|
||||
return
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { DefaultEventsMap, Server, Socket } from 'socket.io'
|
||||
|
||||
export type SocketData = {
|
||||
namespace?: string
|
||||
userId?: number
|
||||
}
|
||||
|
||||
export type SocketServer = Server<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, SocketData>
|
||||
export type SocketWithData = Socket<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, SocketData>
|
||||
Reference in New Issue
Block a user